写入txt文件java

时间:2013-11-02 11:26:08

标签: java file io

我正在为我的学校创建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 个答案:

答案 0 :(得分:2)

使用File对象执行此任务。

 File f = new File("YourPathHere");

一旦拥有了这个文件对象,就可以使用exists函数来检查文件是否存在

 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
相关问题