使用java如何實現向文件中追加內容?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
java向文件中追加內容與讀寫文件內容源碼實例代碼
向文件尾加入內容有多種方法,常見的方法有兩種:
RandomAccessFile類可以實現隨機訪問文件的功能,可以以讀寫方式打開文件夾的輸出流
public void seek(long pos)可以將讀寫指針移到文件尾,參數Pos表示從文件開頭以字節為單位測量的偏移位置,在該位置文件指針。
public void write(int pos)將數據寫到讀寫指針后面,完成文件的追加。參數pos表示要寫入的Byte
通過FileWrite打開文件輸出流,構造FileWrite時指定寫入模式,是一個布爾量,為真時表示寫入的內容添加到已有文件的內容的后面,為假時表示重新寫文件,以前的記錄被清空,默認的值為假。
具體的例子可以參看以下的代碼:
package Characters; import Java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; public class CharactersDemo_03 { // 使用RandomAccessFile實現文件的追加,其中:fileName表示文件名;content表示要追加的內容 public static void appendMethod_one(String fileName, String content) { try { // 按讀寫方式創建一個隨機訪問文件流 RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); long fileLength = raf.length();// 獲取文件的長度即字節數 // 將寫文件指針移到文件尾。 raf.seek(fileLength); // 按字節的形式將內容寫到隨機訪問文件流中 raf.writeBytes(content); // 關閉流 raf.close(); } catch (IOException e) { e.printStackTrace(); } } // 使用FileWriter實現文件的追加,其中:fileName表示文件名;content表示要追加的內容 public static void appendMethod_two(String fileName, String content) { try { // 創建一個FileWriter對象,其中boolean型參數則表示是否以追加形式寫文件 FileWriter fw = new FileWriter(fileName, true); // 追加內容 fw.write(content); // 關閉文件輸出流 fw.close(); } catch (IOException e) { e.printStackTrace(); } } public static void showFileContent(String fileName) { File file = new File(fileName); BufferedReader reader = null; try { System.out.println("以行為單位讀取文件內容,一次讀一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; // 一次讀入一行,直到讀入null為文件結束 while ((tempString = reader.readLine()) != null) { // 顯示行號 System.out.println(line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } } public static void main(String[] args) { String fileName = "C:/temp/append.txt"; String content = "Successful operation!"; System.out.println(fileName + "文件的內容如下:"); CharactersDemo_03.showFileContent(fileName); // 顯示文件內容 // 按RandomAccessFile的形式追加文件 System.out.println("\n按RandomAccessFile的形式追加文件后的內容如下:"); CharactersDemo_03.appendMethod_one(fileName, content); CharactersDemo_03.appendMethod_one(fileName, "\n Game is Over! \n"); CharactersDemo_03.showFileContent(fileName); // 顯示文件內容 // 按FileWriter的形式追加文件 System.out.println("\n按FileWriter的形式追加文件后的內容如下:"); CharactersDemo_03.appendMethod_two(fileName, content); CharactersDemo_03.appendMethod_two(fileName, "\n Game is Over! \n"); CharactersDemo_03.showFileContent(fileName); // 顯示文件內容 } }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。