Apache Common IO là gì? Đọc/ghi file với Common IO

Apache Common IO là gì? Đọc/ghi file với Common IO.

1. Apache Common IO là gì?

Apache Commons là 1 dự án được tạo nên để cung cấp cho các lập trình viên một tập hợp các thư viện chung mà chúng ta hay dùng hàng ngày để code.

Apache Common IO là một phần của dự án apache commons. Nó cung cấp thư viên, các class tiện ích để xử lý file như đọc / ghi, so sánh…

2. Cài đặt Apache Common IO.

Để sử dụng thư viện Common IO bạn có thể tải file .jar tại đây: http://central.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar

Nếu bạn sử dụng maven:

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

3. Các tính năng của Apache Common IO

Apache Common IO là gì? Đọc/ghi file với Common IO

3.1 IOUtils

IOUtils bao gồm các method tiện ích như đọc, ghi và copy. Các method làm việc trên InputStream, OutputStream, Reader và Writer.

Ví dụ dưới đây chúng ta thực hiện đọc dữ liệu từ một URL và in chúng ra:

Cách 1: Sử dụng java.io chuẩn

InputStream in = new URL("https://stackjava.com").openStream();
try {
  InputStreamReader inR = new InputStreamReader(in);
  BufferedReader buf = new BufferedReader(inR);
  String line;
  while ((line = buf.readLine()) != null) {
    System.out.println(line);
  }
} finally {
  in.close();
}

Cách 2: Sử dụng Common IO

InputStream in = new URL( "http://commons.apache.org" ).openStream();
try {
  System.out.println( IOUtils.toString( in ) );
} finally {
  IOUtils.closeQuietly(in);
}

Rõ ràng khi sử dụng IOUtils code sẽ ngắn gọn và tiết kiệm thời gian hơn nhiều.

Một số ví dụ khác với IOUtils:

File fileA = new File("a.txt");
File fileB = new File("b.txt");

// Ghi 2 dòng hello và stackjava.com ra file a.txt với encoding là UTF-8
IOUtils.write("hello \nstackjava.com", new FileOutputStream(fileA), "UTF-8");

// Đọc file và trả về 1 list các dòng của file a.txt
List<String> lines = IOUtils.readLines(new FileInputStream(fileA), "UTF-8");
System.out.println(lines);

// Copy dữ liệu của file a.txt sang file b.txt
IOUtils.copy(new FileInputStream(fileA), new FileOutputStream(fileB));

3.2 FileUtils

 FileUtils cũng thực hiện các chức năng đọc, ghi, copy, so sánh file nhưng nó không làm việc trên InputStream/OutputStream như IOUtils mà làm việc trên các đối tượng File
Ví dụ:
File fileA = new File("a.txt");
File fileB = new File("b.txt");

// Ghi 2 dòng 'xin chào' và 'stackjava.com' ra file a.txt với encoding là UTF-8
FileUtils.writeStringToFile(fileA, "xin chào \nstackjava.com", "UTF-8");

// Đọc dữ liệu của file a.txt thành 1 string
String data = FileUtils.readFileToString(fileA, "UTF-8");
System.out.println(data);

// Đọc dữ liệu của file a.txt thành các dòng và lưu lại thành 1 List
List<String> lines = FileUtils.readLines(fileA, "UTF-8");
System.out.println(lines);

// Copy dữ liệu file a.txt sang file b.txt
FileUtils.copyFile(fileA, fileB);

// xóa file a.txt
FileUtils.forceDelete(fileA);

Kết quả:

xin chào 
stackjava.com
[xin chào , stackjava.com]

3.3. FilenameUtils

Class FilenameUtils bao gồm các method tiện ích để làm việc với file name mà không cần sử dụng đối tuộng file. Khi bạn xử lý file name, bạn có thể gặp các vấn đề khi di chuyển từ môi trường Window sang Unix. Mục tiêu của class này chính là giúp tránh được các vấn đề đó.

Ví dụ:

Windows:
a\b\c.txt           --> ""          --> relative
\a\b\c.txt          --> "\"         --> current drive absolute
C:a\b\c.txt         --> "C:"        --> drive relative
C:\a\b\c.txt        --> "C:\"       --> absolute
\\server\a\b\c.txt  --> "\\server\" --> UNC

Unix:
a/b/c.txt           --> ""          --> relative
/a/b/c.txt          --> "/"         --> absolute
~/a/b/c.txt         --> "~/"        --> current user
~                   --> "~/"        --> current user (slash added)
~user/a/b/c.txt     --> "~user/"    --> named user
~user               --> "~user/"    --> named user (slash added)
String filename = "C:/commons/io/../lang/project.xml";
String normalized = FilenameUtils.normalize(filename);
// result is "C:/commons/lang/project.xml"

3.4. FileSystemUtils

Class FileSystemUtils bao gồm các method tiện ích cho phép làm việc với các file hệ thống để truy cập vào các chức năng không được hỗ trợ bởi JDK. Hiện tại, nó chỉ có duy nhất một method là lấy thông tin còn trống của ổ cứng.

Ví dụ:

FileSystemUtils.freeSpace("C:");       // Windows
FileSystemUtils.freeSpace("/volume");  // *nix

3.5. LineIterator

Class LineIterator cung cấp 1 cách linh hoạt làm việc dựa trên các dòng của file. Các thể hiện có thể được tạo trực tiếp hoặc thông qua các method của FileUtils hoặc IOUtils.

Ví dụ:

LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
  while (it.hasNext()) {
    String line = it.nextLine();
    /// do something with line
  }
} finally {
  LineIterator.closeQuietly(iterator);
}

 

3.6. File Filters

Package org.apache.commons.io.filefilter định nghĩa một interface (IOFileFilter) bao gồm FileFilter và FilenameFilter. Ngoài ra, packagge này còn cung cấp 1 loạt các cài đặt của IOFileFilter. Những filter này có thể sử dụng cho danh sách file hoặc FileDialog.

Ví dụ:

// lọc các file .java
Set<File> allFiles = ...
Set<File> javaFiles = FileFilterUtils.filterSet(allFiles,
    FileFilterUtils.suffixFileFilter(".java"));

// Liệt kê các file ẩn trong ổ C
File dir = new File("C:/");
String[] files = dir.list( HiddenFileFilter.HIDDEN );
for ( int i = 0; i < files.length; i++ ) {
 System.out.println(files[i]);
}

3.7 File Comparator

Package org.apache.commons.io.comparator cung cấp 1 số cài đặt so sánh (java.util.Comparator cho java.io.File). Những bộ so sánh này được dùng để sắp xếp 1 danh sách hoặc mảng file.

List<File> files = Arrays.asList(new File("C:/").listFiles());

// sắp xếp các file theo thứ tự kích thước tăng dần (folder được tính size = 0)
files.sort(SizeFileComparator.SIZE_COMPARATOR);
// sắp xếp các file theo thứ tự kích thước giảm dần (folder được tính size = 0)
files.sort(SizeFileComparator.SIZE_REVERSE);

// sắp xếp các file theo tứ tự name: a -> z
files.sort(NameFileComparator.NAME_COMPARATOR);

// sắp xếp các file theo tứ tự name: z -> a
files.sort(NameFileComparator.NAME_REVERSE);

3.8 Streams

Package org.apache.commons.io.input và org.apache.commons.io.output bao gồm nhiều tiện ích dễ sử dụng được cài đặt từ stream.:

Ví dụ: input

String XML_PATH = "D:/pom.xml";
String INPUT = "This should go to the output.";
    
System.out.println("Input example...");
XmlStreamReader xmlReader = null;
TeeInputStream tee = null;

try {
  // XmlStreamReader
  
  // We can read an xml file and get its encoding.
  File xml = FileUtils.getFile(XML_PATH);
  
  xmlReader = new XmlStreamReader(xml);
  System.out.println("XML encoding: " + xmlReader.getEncoding());
  
  
  // TeeInputStream
  
  // This very useful class copies an input stream to an output stream
  // and closes both using only one close() method (by defining the 3rd
  // constructor parameter as true).
  ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  
  tee = new TeeInputStream(in, out, true);
  tee.read(new byte[INPUT.length()]);

  System.out.println("Output stream: " + out.toString());         
} catch (IOException e) {
  e.printStackTrace();
} finally {
  try { xmlReader.close(); }
  catch (IOException e) { e.printStackTrace(); }
  
  try { tee.close(); }
  catch (IOException e) { e.printStackTrace(); }
}

Kết quả:

Input example...
XML encoding: UTF-8
Output stream: This should go to the output.

Ví dụ: output

String INPUT = "This should go to the output.";
System.out.println("Output example...");
TeeInputStream teeIn = null;
TeeOutputStream teeOut = null;

try {
  
  // TeeOutputStream
  
  ByteArrayInputStream in = new ByteArrayInputStream(INPUT.getBytes("US-ASCII"));
  ByteArrayOutputStream out1 = new ByteArrayOutputStream();
  ByteArrayOutputStream out2 = new ByteArrayOutputStream();
  
  teeOut = new TeeOutputStream(out1, out2);
  teeIn = new TeeInputStream(in, teeOut, true);
  teeIn.read(new byte[INPUT.length()]);

  System.out.println("Output stream 1: " + out1.toString());
  System.out.println("Output stream 2: " + out2.toString());
  
} catch (IOException e) {
  e.printStackTrace();
} finally {
  // No need to close teeOut. When teeIn closes, it will also close its
  // Output stream (which is teeOut), which will in turn close the 2
  // branches (out1, out2).
  try { teeIn.close(); }
  catch (IOException e) { e.printStackTrace(); }
}

Kết quả:

Output example...
Output stream 1: This should go to the output.
Output stream 2: This should go to the output.

 

References:

https://commons.apache.org/proper/commons-io/description.html

https://www.javacodegeeks.com/2014/10/apache-commons-io-tutorial.html

stackjava.com