Sử dụng thư viện NIO để đọc ghi file trong Java

1. Đọc File

Tạo class ReadFileWithJavaNIO.java

package com.loop.io;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

public class ReadFileWithJavaNIO {

  /**
  * Create by Cuder
  *
  * @throws IOException
  */
  public static void main(String[] args) throws IOException {
    File f = new File("resource/textFile.txt");
    ArrayList<String> res = (ArrayList<String>) Files.readAllLines(f
    .toPath());
    for (int i = 0; i < res.size(); i++) {
      System.out.println(res.get(i));
    }
  }
}

Kết quả

Line 1
Line 2
Line 3
Line 4
 Line 5

2. Ghi File

Tạo class WriteNewFileWithJavaNIO.java

package com.loop.io;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;

public class WriteNewFileWithJavaNIO {

  /**
  * Create by Cuder
  *
  * @throws IOException
  */
  public static void main(String[] args) throws IOException {
    ArrayList<String> data = new ArrayList<>();
    data.add("line content 1");
    data.add("line content 2");
    data.add("line content 3");
    data.add("line content 4");
    data.add("line content 5");
    data.add("line content 6");
    File f = new File("resource/fileWrite7.txt");

    Files.write(f.toPath(), data, Charset.forName("UTF-8"),
    StandardOpenOption.CREATE, StandardOpenOption.WRITE);

  }
}

Kết quả fileWrite7.txt

line content 1
line content 2
line content 3
line content 4
line content 5
 line content 6

3. Thêm nội dung file

Nôi dung fileWrite7.txt

line content 1
line content 2
line content 3
line content 4
line content 5
 line content 6

Tạo class AppendContentFileWithJavaNIO.java

package com.loop.io;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;

public class AppendContentFileWithJavaNIO {

  /**
  * Create by Cuder
  *
  * @throws IOException
  */
  public static void main(String[] args) throws IOException {
    ArrayList<String> data = new ArrayList<>();
    data.add("line content 1");
    data.add("line content 2");
    data.add("line content 3");
    data.add("line content 4");
    data.add("line content 5");
    data.add("line content 6");
    data.add("line content 7");
    File f = new File("resource/fileWrite7.txt");

    Files.write(f.toPath(), data, Charset.forName("UTF-8"),
    StandardOpenOption.APPEND, StandardOpenOption.WRITE);
  }
}

Kết quả fileWrite7.txt

line content 1
line content 2
line content 3
line content 4
line content 5
line content 6
line content 1
line content 2
line content 3
line content 4
line content 5
line content 6
 line content 7

Rate this post
Click Here to Leave a Comment Below 0 comments