1. แทนที่เนื้อหาเก่าทั้งหมดที่มีอยู่ด้วยเนื้อหาใหม่.
new FileWriter(file);2. เก็บเนื้อหาเก่าที่มีอยู่แล้วเพิ่มเนื้อหาใหม่ลงในไฟล์(เพิ่มพารามิเตอร์เป็น true).
new FileWriter(file,true);ต่อไปนี้คือตัวอย่างเนื้อหาในไฟล์ "C:\\users\\....\\newfile.txt" ที่มีอยู่ก่อนที่จะเขียนเพิ่มภายหลัง.
Text Beforeเขียนเนื้อหาเพิ่มในไฟล์โดยใช้ 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 doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
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
0 comments:
Post a Comment