2013-11-02 209 views
0

我正在为我的学校创建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 
       } 
      } 
+1

我不能看到写在你的代码文件中的一部分,但检查一个文件或文件夹是否存在需要使用具有File对象的存在的方法 –

+0

@Richard刺痛究竟如何我可以从Formatter转换为文件对象?谢谢 – Edgars

+1

请参阅sumitb的解决方案。如果所有的syatems都注意“/”只是窗口中的文件夹分隔符 –

回答

2

使用File对象完成这个任务。

File f = new File("YourPathHere"); 

一旦你有,你可以使用这个文件对象存在的功能检查,如果你想将内容添加到现有的文件(技术上称为文件存在与否

f.exists() //returns true if mentioned file exists else return false 

之后附加操作),您可以告诉FileWriter对象以附加模式创建文件流。

output = new BufferedWriter(new FileWriter(yourFileName, true)); //second argument true state that file should be opened in append mode 
+0

非常感谢,代码的最后一行保存了我的一天:) – Edgars