我正在爲我的學校創建java項目,但現在我卡在這裏。寫入到txt文件java
我想創建一個程序來創建.txt文件,並將我的輸入從鍵盤寫入它。 但在此之前它會檢查文件是否已經存在。因此,程序不會創建具有相同名稱的新文件,但它會將輸入添加到以前插入的數據。
有時候,我每次運行該程序時都會向該.txt文件添加信息。 在這一刻,一切正常,但除了檢查,如果該文件已經存在。我試圖添加exists();但沒有成功。
我是這個所以請給我一個提示並非所有的解決方案:) 在此先感謝!
代碼
private Formatter output; //object
public static String user_name() {
String user_name=System.getProperty("user.name");
return user_name;
};
public void openFile(){
try {
output = new Formatter(user_name()+".txt"); //here I tried to add exists() method to check if the file exists already. but it responded //with undefined method error.
}
catch (SecurityException securityException)
{
System.err.println("Jums nav atļauja rediģēt šo failu");
System.exit(1); //izejama no programmas
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.print("Kļūda atverot failu");
System.exit(1); //izejama no programmas
}
}
我不能看到寫在你的代碼文件中的一部分,但檢查一個文件或文件夾是否存在需要使用具有File對象的存在的方法 –
@Richard刺痛究竟如何我可以從Formatter轉換爲文件對象?謝謝 – Edgars
請參閱sumitb的解決方案。如果所有的syatems都注意「/」只是窗口中的文件夾分隔符 –