Create New Text Files with Different Names in Java

亡梦爱人 提交于 2019-12-10 22:13:57

问题


Every time the code is executed I want a new Text File to be created.

The Text File should be called Person1.

Next time code is executed the Text File should be called Person2.

Then again the Text File should be called Person3. etc, etc....

At the moment, I'm able to create a Text File named "Person1" but can't create another Text File named "Person2".

private int fileNumber = 1;
fileNumber = fileNumber++;

public static void main(String[] args) {
        try {
            FileWriter fw = new FileWriter("Person" + fileNumber + ".txt");
            PrintWriter pw = new PrintWriter(fw);

            pw.println("Hello you created a text file");

            pw.close();
        }
        catch (IOException e)
        {
            System.out.println("Error!");

        }
}

回答1:


Check for the file. If exists then increment the index

File file = new File("E:\\" + "Person1" + ".txt");
int increase=1;
while(file.exists()){
     increase++;
     file = new File("E:\\" + "Person" + increase+ ".txt");
} 
if(!file.exists()) {
   try {

    String content = textfile.toString();
    file.createNewFile();

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();

    System.out.println("Done");

}catch (IOException e){
   }



回答2:


Upon creating a new file, you should check if the file with such fileNumber or index already exists. While a file with such index exists, the index should be incremented. Finally, you create a new file with an index that does not exist.

Say you created an abstract representation of a file and now want to rename it to the first available index. Let's assume other files are located at C:\tmp:

File newFile;

int index = 1;
String parent = "C:\\tmp"
String name = "Person";
while ((newFile = new File(parent, name + index)).exists()) {
    index++;
}

/* Here you have a newFile with name set to the first available index */

Or if you want to consider having an extension:

File newFile;

int index = 1;
String parent = "C:\\tmp"
String name = "Person";
String extension = ".txt";
while ((newFile = new File(parent, name + index + extension)).exists()) {
    index++;
}

/* Here you have a newFile with name set to the first available index and extension */

UPDATE: Using the Java 8 NIO API, I've created the following method to return a Path object for the first available path that does not yet exist on the file system:

/**
 * Returns the first available {@code Path} with a unique file name. The
 * first available path means that, if a file with the specified
 * <tt>path</tt> exists on disk, an index is appended to it. If a file with
 * that path still exists, index is incremented and so on, until a unique
 * path is generated. This path is then returned.
 * <p>
 * If a file with the specified <tt>path</tt> does not exist, this method
 * trivially returns <tt>path</tt>.
 * <p>
 * For an example, if the parent directory of the specified path already
 * contains <tt>file.txt</tt>, <tt>file-0.txt</tt> and <tt>file-1.txt</tt>,
 * and the file name of this path is <tt>file.txt</tt>, then a path with
 * file name <tt>file-2.txt</tt> is returned.
 * 
 * @param path path from which the first available is returned
 * @return a path with a unique file name
 */
public static Path firstAvailable(Path path) {
    if (!Files.exists(path))
        return path;

    int namingIndex = 0;
    String name = path.getFileName().toString();
    String extension = "";

    int dotIndex = name.lastIndexOf('.');
    if (dotIndex > 0) {
        extension = name.substring(dotIndex);
        name = name.substring(0, dotIndex);
    }
    name += "-";

    while (Files.exists(path)) {
        path = path.resolveSibling(name + namingIndex + extension);
        namingIndex++;
    }
    return path;
}



回答3:


There are two different way to do this based on your program execution. If you want to keep the program running and within that are calling that function, then you can keep the last generated file number and increment by 1. For example, your last generated file name is Person4, so, next one will be Person5 by incrementing the number of the variable. But if you wish to run the program from beginning each time, then you have to read the index already written to your directory. When you read the filename from the directory, you can use substring(5, index.length) which will give you the number. Then increment that number for the next file.



来源:https://stackoverflow.com/questions/35971308/create-new-text-files-with-different-names-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!