簡體   English   中英

寫入txt文件java

[英]write to txt file java

我正在為我的學校創建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對象執行此任務。

 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM