2017-08-15 92 views
0

所以這裏的問題, 我堆了如何創建,打開,寫入和讀取文件,與此代碼的Java如何創建,打開,寫入和讀取,然後關閉該文件

import java.util.*; 
import java.io.*; 

class class_Name{ 

Formatter x;      // Variable: creating new file 
File file = new File("file.txt"); // Variable: check file existence 

    //creating txt file 
    public void creating_file(){ 
     try{ 
      x = new Formatter("file.txt"); 
     }catch(Exception e){ 
      System.out.println("you got an error"); 
     } 
    } 

    public int check_file(){ 
     if(file.exists()){ 
      return 1; // in main method, check if file already exists just pass from creating file 
     }else{ 
      return 0; // in main method if return value 0, then it create new file with "public void creating_file()" method 
     } 
    } 

所以問題是當我試圖在文件中寫入某些東西時,我使用類Formatter,並且它始終格式化之前的所有文本數據,並且如果public int check_file()等於1,則類Formatter將不起作用,因爲它使用Formatter從創建文件跳過類,不能在文件中只寫了,因爲變量x未定義

這是我的代碼怎麼寫文本文件中的

public void recording_to_file(){ 
     x.format(format, args); 
    } 

,並關閉文件,我需要處理錯誤這樣

public void close_file(){ 
     try{ 
      x.close(); 
     }catch(Exception e){ 
      file.close(); 
     } 
    } 

} 

只是有萬噸級的,我需要做的事情只有一個文件,也可能有一個簡單的類,可以做一個像(寫,打開,閱讀,關閉),我在新的java,我覺得也許在這裏我能得到幫助,謝謝

+0

很難理解,你的故事有完全無關 –

+0

看看類'FileReader'和'FileWriter'(恕我直言)採取編碼。 [reader](https://docs.oracle.com/javase/8/docs/api/index.html?java/io/FileReader.html)和[writer](http://docs.oracle.com/javase /8/docs/api/java/io/FileWriter.html)。您不需要將布爾轉換爲0或1 btw。按原樣使用它。 – Matt

回答

0

看看這個。 FileWriter構造函數的第二個參數(true)告訴它只添加數據,而不是覆蓋任何數據。

import java.util.*; 
import java.io.*; 

class SomeClass{ 

    Formatter x;      
    File file = new File("file.txt"); 

    public void creating_file(){ 
     try{ 
      x = new Formatter(new FileWriter(file, true)); 
     }catch(Exception e){ 
      System.out.println("you got an error"); 
     } 
    } 

    public boolean check_file(){ 
     return file.exists(); 
    } 
} 
相關問題