我正在为我的学校创建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都注意“/”只是窗口中的文件夹分隔符 –