java追加文件


public class AppendToFile { 
/** 
* A方法追加文件:使用RandomAccessFile 
*/ 
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(); 
} 
} 

/** 
* B方法追加文件:使用FileWriter 
*/ 
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 main(String[] args) { 
String fileName = "C:/temp/newTemp.txt"; 
String content = "new append!"; 
//按方法A追加文件 
AppendToFile.appendMethodA(fileName, content); 
AppendToFile.appendMethodA(fileName, "append end. \n"); 
//顯示文件內容 
ReadFromFile.readFileByLines(fileName); 
//按方法B追加文件 
AppendToFile.appendMethodB(fileName, content); 
AppendToFile.appendMethodB(fileName, "append end. \n"); 
//顯示文件內容 
ReadFromFile.readFileByLines(fileName); 
} 
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM