【问题标题】:Create New Text Files with Different Names in Java在 Java 中创建具有不同名称的新文本文件
【发布时间】:2016-06-28 12:47:59
【问题描述】:

每次执行代码时,我都希望创建一个新的文本文件。

文本文件应称为 Person1。

下次执行代码时,文本文件应称为 Person2。

然后文本文件应该再次称为 Person3。等等等等……

目前,我可以创建一个名为“Person1”的文本文件,但无法创建另一个名为“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!");

        }
}

【问题讨论】:

  • 下次执行代码时,文本文件应该被称为 Person2 你的意思是下次启动程序?
  • 不,代码可以被不同的用户多次执行。 1 个用户可以创建多个文本文件,但文本文件需要不同的名称。
  • 请将“e.printStackTrace()”放在catch块中,并将结果添加到问题中。有了这个,您可能就可以自己诊断问题了。
  • 您的代码错误地假设值fileNumber 将在每次有人运行程序时继续存在。情况并非如此:每次运行程序时,由同一用户或不同用户运行,变量fileNumber 将重新启动为1。查看答案;他们检查文件 PersonX.txt (X=1,2,3...) 是否已经存在。

标签: java text-files filewriter printwriter


【解决方案1】:

在创建新文件时,您应该检查带有fileNumberindex 的文件是否已经存在。 虽然存在具有此类index 的文件,但index 应递增。最后,使用不存在的index 创建一个新文件。

假设您创建了一个文件的抽象表示,现在想要将其重命名为第一个可用的index。假设其他文件位于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 */

或者如果您想考虑扩展:

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 */

更新:使用 Java 8 NIO API,我创建了以下方法来为文件系统上尚不存在的第一个可用路径返回 Path 对象: p>

/**
 * 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;
}

【讨论】:

  • 我想保留姓名、Person1、Person2 等...但是之后如何创建另一个?
【解决方案2】:

检查文件。如果存在则增加索引

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){
   }

【讨论】:

    【解决方案3】:

    根据您的程序执行情况,有两种不同的方法可以做到这一点。如果您想保持程序运行并在其中调用该函数,那么您可以保留最后生成的文件编号并递增 1。例如,您最后生成的文件名是 Person4,因此,下一个将是 Person5,递增变量的编号。但是,如果您希望每次都从头开始运行程序,则必须读取已写入目录的索引。当您从目录中读取文件名时,您可以使用 substring(5, index.length) 这将为您提供数字。然后为下一个文件增加该数字。

    【讨论】:

      【解决方案4】:

      试试这个。只需更改 for 循环中的 i 值即可创建您需要的文件数

      File file;    
      
      for (int i = 21; i < 32; i++) {        
          file = new File("Practica" + Integer.toString(i) + ".java");
          try {
              file.createNewFile();
          } catch (Exception e) {}
      }
      

      【讨论】:

        【解决方案5】:
            try {
                int index= 0;
                File file = new File("folder\\" + "filename" + ".txt");
                while (file.exists()) {
                    index++;
                    file = new File("folder\\" + "filename" + index + ".txt");
                }
                if (!file.exists()) {
                    // create file
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-17
          • 2018-07-03
          • 1970-01-01
          相关资源
          最近更新 更多