ตัว FileWritter เป็น character stream
ที่เขียนข้อมูลที่เป็นตัวอักษรลงไฟล์.
โดยทั่วไปแล้วเราจะทำการแทนที่เนื้อหาเก่าที่มีอยู่ด้วยเนื้อหาใหม่
อย่างไรก็ตาม
เราสามารถเก็บเนื้อหาเก่าที่มีอยู่แล้วเพิ่มเนื้อหาใหม่ได้เช่นเดียวกัน
ซึ่งมีหลักการดังนี้ :
1. แทนที่เนื้อหาเก่าทั้งหมดที่มีอยู่ด้วยเนื้อหาใหม่.
2. เก็บเนื้อหาเก่าที่มีอยู่แล้วเพิ่มเนื้อหาใหม่ลงในไฟล์(เพิ่มพารามิเตอร์เป็น true).
|
new FileWriter(file,true);
|
ต่อไปนี้คือตัวอย่างเนื้อหาในไฟล์ "C:\\users\\....\\newfile.txt" ที่มีอยู่ก่อนที่จะเขียนเพิ่มภายหลัง.
เขียนเนื้อหาเพิ่มในไฟล์โดยใช้ FileWriter(file,true)
package demo.file;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class AppendToFileExample {
/**
* @param args
*/
public static void main(String[] args) {
try{
String data = " This content will append to the end of the file";
File file =new File("C:\\users\\nopphanan7\\newfile.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}
}
ผลลัพธ์ที่ได้คือ(ให้ไปดูที่ C:\\users\\....\\newfile.txt)
Text Before This content will append to the end of the file
ไม่มีความคิดเห็น:
แสดงความคิดเห็น