开发者

How to create multiple files, generating a random name for each file

开发者 https://www.devze.com 2023-02-15 01:04 出处:网络
What I\'m trying to do is create lots of random files but I\'m just completely lost. The code below just doesn\'t work, I\'m wondering why it doesn\'t work and what can i do to fix it.

What I'm trying to do is create lots of random files but I'm just completely lost. The code below just doesn't work, I'm wondering why it doesn't work and what can i do to fix it.

import java.io.*;
import java.util.*;

public class main {
  public static void main(String arg[]){

      Random rn = new Random();
      int randn = 1+rn.nextInt(999999990);
      String I_S = Integer.toString(randn);

      Formatter file;


      try{

          for(int i = 0; i < 9999999; i++){
              file = new Formatter("%s.txt", I_S);
          }
      }
      catch(Exception ex){
        System.err.println("Error");
  开发者_如何学C    }

  } 

}


By just generating random numbers, you may end up creating / overwriting the same file multiple times. To have an absolutely unique set, do something like this:

    final int MAX = 9999999;

    List<Integer> list = new ArrayList<Integer>();

    for (int i = 0; i < MAX; i++) {
        list.add(i);
    }

    Collections.shuffle(list);

    for (int i = 0; i < MAX; i++) {
        // create files here
    }


How to create multiple files, generating a random name for each file.

You probably want to have a look at File.createTempFile.

Looking at your code, you probably want something like

Random rn = new Random();
String file;

for (int i = 0; i < 100; i++)
    file = String.format("%i.txt", 1+rn.nextInt(999999990));


I'm not sure exactly what you expect this code to achieve, but right now it effectively does nothing.

You're looping many, many times creating an instance of Formatter each time. This is not a file; instead, it's a class that knows how to replace tokens in strings to create other strings.

I think you're confused by the description of the constructor you're calling and the purpose of the class as a whole. The constructor takes as its first argument the name of the file to use for output - in your case, this will always be %s.txt. The second argument is the name of a supported charset to use for encoding the String to the file.

This code will always fail because:

  1. Your I_S variable, e.g., "56437890" is not a valid encoding (whereas "UTF-8" would be). Hence the constructor will probably throw an exception when trying to work out the encoding scheme.
  2. Even if the charset was miraculously right, you're still trying to write to the same file (%s.txt) every time, so you wouldn't get the desired multi-file behaviour.
    This string may not even be a valid filename, depending on your OS, and so if the Formatter tries to create the file it will throw an exception.
  3. If both arguments miraculously work out, you're still not actually doing anything with the formatter, so it doesn't have anything to write out to the file which thus may not be created.
  4. Finally, you're not updating your random variable (I_S) in the loop - it gets set once, and then maintains the same value forever. So even if all the above problems weren't issues, you'd still create the same (single) randomly-named file over and over and over again.

And as I noted in the comments, when it fails, you're catching and swallowing the exception so you have absolutely no way of knowing what went wrong.

Fundamentally I think you're confused about the purpose of the Formatter class, and since I don't know what you're trying to achieve (should the files be empty? Have specific text in?) I can't suggest something which definitely works. However, if you just want to create empty files, try something like this inside your loop:

String filename = "%s.txt".format(I_S);
File file = new File(filename);
file.createNewFile();
// Add some logic to update the random variable here!

As a final point, adarshr's answer is entirely right that you stand a nontrivial chance of repeating random numbers, so you won't get exactly as many files as you expect. The answer goes on to describe a good way to avoid this, and it's worth following.


You may want to look into writing something more like this:

void Write()
{
    try {
        for(int i = 0; i < MAX_FILES; i++) {
            FileWriter outFile = new FileWriter("C:\File" + i.toString() + ".txt");
            PrintWriter out = new PrintWriter(outFile);

            // Write text to file
            out.println("This is line 1");
            out.println("This is line 2");
            out.print("This is line3 part 1, ");
            out.println("this is line 3 part 2");
            out.close();
        }
    } 
            catch (IOException e) {
        e.printStackTrace();
    }
}
// obviously this requires a import java.io.*; at the top of the class

Source: http://www.abbeyworkshop.com/howto/java/writeText/index.html

0

精彩评论

暂无评论...
验证码 换一张
取 消