Commons Io 简明教程
Apache Commons IO - FileUtils
提供操作文件的方法,例如移动、打开、检查是否存在、读取文件等。这些方法使用 File Object。
Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.
Class Declaration
下面是 org.apache.commons.io.FileUtils 类的声明 -
Following is the declaration for org.apache.commons.io.FileUtils Class −
public class FileUtils
extends Object
Features of FileUtils
以下为 FileUtils 的特性 -
The features of FileUtils are stated below −
-
Methods to write to a file.
-
Methods to read from a file.
-
Methods to make a directory including parent directories.
-
Methods to copy files and directories.
-
Methods to delete files and directories.
-
Methods to convert to and from a URL.
-
Methods to list files and directories by filter and extension.
-
Methods to compare file content.
-
Methods to file last changed date.
-
Methods to calculating a checksum.
Example of FileUtils Class
以下是我们需要解析的输入文件 -
Here is the input file we need to parse −
Welcome to TutorialsPoint. Simply Easy Learning.
IOTester.java
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class IOTester {
public static void main(String[] args) {
try {
//Using FileUtils
usingFileUtils();
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
public static void usingFileUtils() throws IOException {
//get the file object
File file = FileUtils.getFile("input.txt");
//get the temp directory
File tmpDir = FileUtils.getTempDirectory();
System.out.println(tmpDir.getName());
//copy file to temp directory
FileUtils.copyFileToDirectory(file, tmpDir);
//create a new file
File newTempFile = FileUtils.getFile(tmpDir, file.getName());
//get the content
String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());
//print the content
System.out.println(data);
}
}