Làm thế nào để chèn tiếp nội dung vào một tập tin TXT có sẵn bằng BufferedWriter trong Java? (How to append content to TXT file with BufferedWriter in Java?)







Bài viết này tôi sẽ hướng dẫn cách chèn nội dung vào một TXT đã tồn tại và có nội dung trước đó, bằng cách sử dụng BufferedWriter trong ngôn ngữ lập trình Java.








Đầu tiên bạn cần chuẩn bị một tập tin TXT có sẵn nội dụng như sau:



AppendToFileBufferedWriter.java
/**
 * @(#)AppendToFileBufferedWriter.java
 *
 * AppendToFileBufferedWriter application
 *
 * @author developer.bnson@gmail.com
 * @version 1.00 2014/3/10
 */

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileBufferedWriter {
   
    public static void main(String[] args) {
       
        try {
           
            String contentAppend = " \r\n -- VNLIVES.NET - Please Like to help me improving website.";

            File file =new File("D:\\Z-Test\\Demo\\FileWriteByJava.txt");

            //If file doesnt exists, then create it.
            if(!file.exists()){
                file.createNewFile();
            }

            //True is append file
            FileWriter fw = new FileWriter(file.getPath(),true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(contentAppend);
            bw.close();

            System.out.println("File append is complete.");

        } catch(IOException e) {
            e.printStackTrace();
        }
       
    }
}

Kết quả sau khi thực thi sẽ là:
File append is complete.

Tiếp theo bạn mở lại tập tin TXT để kiểm tra kết quả.






































No comments:

Post a Comment