I/O流(四)—java如何添加到文件尾
生活随笔
收集整理的這篇文章主要介紹了
I/O流(四)—java如何添加到文件尾
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如何添加到文件尾:
* 默認的情況是,新內容覆蓋舊內容。 * 添加到尾的兩種方式 * 構造成器中指示定參數 * 使用隨機文件* 把第二個參數設為true * new FileOutputStream(“a.txt”,true) * 這樣的弱點是:不能在舊的內容上修改,只能添加隨機讀寫
* 隨機的含義 * 可以跳到任意位置讀寫 * 跳的單位是:字節 * 讀寫可以交替進行 * 使用類: RandomAccessFile* 構造器 * (String name, String mode) * 需要選定模式 * 可用的模式 * “r” 只能讀,文件不存在會報錯 * “rw” 讀寫方式,文件不存在會創建 * 二進制才能隨機讀寫 * RandomAccessFile * length() 文件長度 * seek(long pos) 文件指針定位 * 大量重載的 read 和 write * 隨機讀寫時是二進制的觀點 * 為什么不能是文本的觀點?行的長度可能不相等。 * 這個類并不能抽象為InputStream,或者OutputStream。流是個序列,不能隨機訪問。java添加到文件尾的兩種方式:
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 AppendtoFile {public static void appendMethodA(String fileName, String content) {try {// 打開一個隨機訪問文件流,按讀寫方式RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");// 文件長度,字節數long fileLength = randomFile.length();//將寫文件指針移到文件尾。randomFile.seek(fileLength);randomFile.writeBytes(content);randomFile.close();} catch (IOException e) {e.printStackTrace();}}public static void appendMethodB(String fileName, String content) {try {//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件FileWriter writer = new FileWriter(fileName, true);writer.write(content);writer.close();} catch (IOException e) {e.printStackTrace();}}public static void readFileByLines(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) {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 = "F:/私人物品劉夢冰/學習資料/exercise/Customer01.txt";String content = "new append!";//按方法A追加文件AppendtoFile.appendMethodA(fileName, content);AppendtoFile.appendMethodA(fileName, "append end. \n");//顯示文件內容AppendtoFile.readFileByLines(fileName);//按方法B追加文件AppendtoFile.appendMethodB(fileName, content);AppendtoFile.appendMethodB(fileName, "append end. \n");//顯示文件內容AppendtoFile.readFileByLines(fileName);} }運行結果:
最開始的文件:
添加內容后的文件:
總結
以上是生活随笔為你收集整理的I/O流(四)—java如何添加到文件尾的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: I/O流(三)—对象的序列化和反序列化
- 下一篇: java开发微信二维码