Java學習筆記——讀寫追加文件內容

實際項目中,拿到文本文件如果需要在文件中替換或者添加內容,可以用java.io.RandomAccessFile實現。

原文件內容:

1、最簡單的文件末尾添加

需要在網頁中添加一個打印網頁的按鈕,上碼

import java.io.RandomAccessFile;

public class MyTest20200405 {
	
	public static void main(String[] args) throws Exception {
		try {
			String sFilePath = "F:/study/20200520/mytest0520.txt";
			RandomAccessFile raf = new RandomAccessFile(sFilePath,"rw");
			raf.seek(raf.length());//定位到文件末尾
			String sAddStr = "MyTest20200405";
			raf.write(sAddStr.getBytes("UTF-8"));//追加新的內容
			raf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

修改後的文件內容

頁面效果:

2、在文件內容中間添加

需要先定位添加內容的位置,並將該位置後面的內容臨時存起來,再將添加的內容寫上去,寫完最後在把原來的內容追加上去。

不然會直接把原來的內容覆蓋掉。

比如這樣:

import java.io.RandomAccessFile;

public class MyTest20200405 {
	
	public static void main(String[] args) throws Exception {
		try {
			String sFilePath = "F:/study/20200520/mytest0520.html";
			RandomAccessFile raf = new RandomAccessFile(sFilePath,"rw");
			String sAddStr = "<input type='button' name='print' value='打印' οnclick='pagePrint()'>";
			sAddStr += "<script language='javascript'>"
					+ "function pagePrint(){"
					+ "document.all('print').style.display='none';"
					+ "window.print();"
					+ "}"
					+ "</script>";
			raf.seek(77);//定位到指定位置
			raf.write(sAddStr.getBytes());//追加新的內容
			raf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

覆蓋效果

待續。。。。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章