簡體   English   中英

如何在Java NetBeans中創建新的“ .txt”文件而不覆蓋以前保存的文件?

[英]how can i create a new “.txt” file in java netbeans without overwriting the previous saved file?

如何在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);
    }

我猜這是一個硬件程序,所以我不應該給您確切的代碼。 但是您可以做的是檢查文件是否存在,如果不存在,請寫入文件,否則創建一個新文件。 像這樣的東西:

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

您可以檢查文件是否已經存在:

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

你想要這樣的東西嗎?

與其對聲明中的文件名進行硬編碼,

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循環,將當前迭代添加到文件名中,以便動態生成新名稱。

創建唯一文件名的最簡單方法是將日期和時間放入文件名中。 像這樣。

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM