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 = "D:/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); // 顯示文件內容
}
}