在java中写入txt文件

在java中写入txt文件,java,file,io,Java,File,Io,我正在为我的学校创建java项目,但现在我被困在这里 我想创建一个程序来创建.txt文件,并将键盘输入的内容写入其中。 但在此之前,它会检查该文件是否已经存在。因此程序不会创建同名的新文件,但会将该输入添加到先前插入的数据中 换句话说,每次我运行该程序时,它都可以向该.txt文件添加信息。 此时,一切正常,但除了检查该文件是否已存在。我试图添加exists();但是没有成功 我对此感到很抱歉,所以请给我一个提示(并非所有的解决方案:) 提前谢谢 代码 private Formatter outp

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

我在代码中看不到写入文件的部分,但要检查文件或文件夹是否存在,需要使用具有exists的file对象method@Richard我怎样才能从格式化程序转换到文件对象?感谢sumitb的回答,解决了这个问题。如果所有系统都注意“/”仅是windows中的文件夹分隔符,那么该程序将是windows还是所有系统的程序(始终是最好的)?请参阅各种非系统特定分隔符,包括路径分隔符