【问题标题】:how can i create a new ".txt" file in java netbeans without overwriting the previous saved file?如何在 java netbeans 中创建一个新的“.txt”文件而不覆盖以前保存的文件?
【发布时间】:2016-01-26 16:05:01
【问题描述】:

如何在 java netbeans 中创建一个新的“.txt”文件而不覆盖以前保存的文件?

这是我的代码,我使用了设置文件名的方法,因为我还不知道如何创建一个新的 .txt 文件并且不覆盖之前的文件

        File file = new File("Basic Student Information.txt");
    try {
        Files.write(Paths.get("Basic Student Information.txt"),list);
        Scanner scan = new Scanner(file);
        //while(scan.hasNext()){
        //    JOptionPane.showMessageDialog(null,scan.nextLine());
        //}
    } catch (IOException ex) {
        Logger.getLogger(StudentInfo.class.getName()).log(Level.SEVERE, null, ex);
    }

【问题讨论】:

  • @Satya:感谢您的指正。

标签: java text file-io


【解决方案1】:

我猜这是一个硬件程序,所以我不应该给你确切的代码。但是您可以做的是检查文件是否存在,如果不存在则写入它,否则创建一个新文件。像这样:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
// do something
} else {
//create a new file and write to it
}

【讨论】:

    【解决方案2】:

    你可以检查文件是否已经存在:

    File f = new File("name.txt");
    if(f.exists() && !f.isDirectory()) { 
       // create file with other name
    }else{
       // Use that filename
    }
    

    你想要这样的东西吗?

    【讨论】:

      【解决方案3】:

      而不是在声明中硬编码文件名,

      File file = new File("Basic Student Information.txt");
      

      尝试将文件名设置为变量本身

      String fileName = "something.txt";
      File file = new File(fileName);
      

      如果您的文件将被覆盖,只需编辑字符串即可。

      if(f.exists() && !f.isDirectory()) 
      { 
         fileName = "somethingelse.txt";
      }
      else
      {
         // Use filename
      }
      //Name file as normal
      

      如果您要多次执行此操作,您甚至可以设置一个 for 循环,将当前迭代添加到文件名,以便动态生成新名称。

      【讨论】:

        【解决方案4】:

        创建唯一文件名的最简单方法是将日期和时间放在文件名中。像这样。

        Basic Student Information 2016/01/26 11:04:02.txt
        

        这是一种方法:

        package com.ggl.testing;
        
        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        
        public class CreateFileName {
        
            public static void main(String[] args) {
                CreateFileName createFileName = new CreateFileName();
                String fs = createFileName.createFileName("Basic Student Information",
                        "txt");
                System.out.println(fs);
            }
        
            public String createFileName(String name, String extension) {
                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Date currentDate = new Date();
                return name + " " + dateFormat.format(currentDate) + "." + extension;
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2015-06-20
          • 2018-02-18
          • 2018-05-22
          • 1970-01-01
          • 1970-01-01
          • 2012-06-18
          • 2012-11-23
          • 2019-10-10
          • 2019-09-20
          相关资源
          最近更新 更多