Trong bài viết này chúng ta sẽ tìm hiểu cách ghi nối thêm nội dung vào một file trong Java. Ví dụ bạn có file A đã có nội dung sẵn rồi, nhưng muốn ghi bổ sung thêm nữa thì có thể thực hiện bằng Java code rất đơn giản.

Có hai cách để nối thêm:

  • Sử dụng FileWriter và BufferedWriter: Trong cách này chúng ta sẽ có một hoặc nhiều chuỗi, và sẽ nối các chuỗi đó vào file. File có thể được ghi thêm chỉ bằng đối tượng FileWriter, tuy nhiên nếu sử dụng thêm BufferedWriter thì sẽ tăng tốc độ ghi file.
  • Sử dụng PrintWriter: Đây là một trong những cách tốt nhất để chắp thêm nội dung vào một file. Bất cứ điều gì bạn viết bằng cách sử dụng đối tượng PrintWriter sẽ được thêm vào file.

1. Ghi nối vào file bằng FileWriter và BufferedWriter

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo
{
   public static void main( String[] args )
   {   
      try{
        String content = "This is my content which would be appended " +
            "at the end of the specified file";
        //Specify the file name and path here
        File file =new File("<a href="file:///C://myfile.txt">C://myfile.txt</a>");
        /* This logic is to create the file if the
         * file is not already present
         */
        if(!file.exists()){
           file.createNewFile();
        }
        //Here true is to append the content to file
        FileWriter fw = new FileWriter(file,true);
        //BufferedWriter writer give better performance
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(content);
        //Closing BufferedWriter Stream
        bw.close();
    System.out.println("Data successfully appended at the end of file");
      }catch(IOException ioe){
         System.out.println("Exception occurred:");
         ioe.printStackTrace();
       }
   }
}

Output:

Data successfully appended at the end of file

Giả sử ban đầu file myfile.txt có nội dung như sau:

Lets say myfile.txt content was:

Sau khi chạy chương trình này thì file sẽ có nội dung là:

This is the already present content of my fileThis is my content which 
would be appended at the end of the specified file

2. Ghi nối vào file bằng PrintWriter

PrintWriter cho phép bạn sử dụng linh hoạt hơn. Sử dụng nó bạn có thể dễ dàng định dạng nội dung sẽ được thêm vào file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
class AppendFileDemo2
{
   public static void main( String[] args )
   {   
      try{
          File file =new File("<a href="file:///C://myfile.txt">C://myfile.txt</a>");
          if(!file.exists()){
            file.createNewFile();
          }
          FileWriter fw = new FileWriter(file,true);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter pw = new PrintWriter(bw);
          //This will add a new line to the file content
          pw.println("");
          /* Below three statements would add three
           * mentioned Strings to the file in new lines.
           */
          pw.println("This is first line");
          pw.println("This is the second line");
          pw.println("This is third line");
          pw.close();
      System.out.println("Data successfully appended at the end of file");
       }catch(IOException ioe){
           System.out.println("Exception occurred:");
           ioe.printStackTrace();
      }
   }
}

Output:

Data successfully appended at the end of file

Giả sử ban đầu file có nội dung là:

This is the already present content of my file

Sau khi chạy chương trình thì file có nội dung như sau:

This is the already present content of my file
This is first line
This is the second line
This is third line

Trên là hai cách ghi nối thêm dữ liệu vào file bằng ngôn ngữ Java. Bạn nên sử dụng PrintWriter vì nó linh hoạt hơn rất nhiều trong việc định dạng nội dung sẽ được thêm vào.

Theo: freetuts.net

 

 

ĐĂNG KÝ THÀNH VIÊN

NẾU NỘI DUNG HỮU ÍCH HÃY XEM QUẢNG CÁO ĐỂ ỦNG HỘ

NẾU NỘI DUNG HỮU ÍCH HÃY XEM QUẢNG CÁO ĐỂ ỦNG HỘ

Được quan tâm nhiều nhất

  • Phim Ngắn Đột Kích - Phiên bản 10 năm trước

  • iPhone 11 Pro Max Teardown - Tiny Motherboard & BIG Battery!

  • Apple Watch Series 4 Teardown

  • Apple Watch Series 5 Teardown - Always on Display Explained

Bạn thấy bài viết này thế nào?
Thể hiện yêu thương tác giả ở đây nhé!

Thích bài viết

thích

Chia sẻ ngay!

phuongle

Thành viên từ: 10/12/2019

Điểm uy tín: 5,987

SMod: 1,289 hướng dẫn đã chia sẻ

Team

Lập Trình Thành viên của Lập Trình

1 Thành viên

1,289 bài viết

Thêm bình luận

Bình luận bằng tài khoản Facebook

After viewing your support content - Please click advertisement for Support & Donate us team! Đóng