How to use the Commons IO library for files and stream reading and writing
Use the Commons IO library to perform files and stream read and write
Apache Commons IO library is a widely used Java class library that provides many convenient methods to implement files and stream read and write operations.This article will introduce how to use the Commons IO library to read and write files and flow, and provide some Java code examples.
1. File read
Using the Commons IO library can easily read file content.First, the following dependencies need to be introduced:
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
Then, you can read the content of the file with the following code:
try {
File file = new File("path/to/file");
String content = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
System.out.println(content);
} catch(IOException e) {
e.printStackTrace();
}
The "path/to/file" in the above code needs to be replaced with the path of the actual file.The ReadFiletring method reads the file content as a string and uses UTF-8 encoding.
2. Writing of files
Using the Commons IO library can easily write the content into the file.Below is an example code written by a file:
try {
File file = new File("path/to/file");
String content = "content you need to write";
FileUtils.writeStringToFile(file, content, StandardCharsets.UTF_8);
System.out.println ("The file is successfully written!");
} catch(IOException e) {
e.printStackTrace();
}
The "path/to/file" in the above code needs to be replaced with the path of the actual file.WriteStringtofile method will write the specified content in the file in UTF-8 coding.
Third, stream reading and writing
In addition to files, the Commons IO library also provides read and write support for streaming.The following is a sample code that reads content from the input stream and writes to the output stream:
try {
InputStream input = ...; // Assuming a input stream
OutputStream Output = ...; // Assume that there is an output stream
FileUtils.copy(input, output);
System.out.println ("The reading and writing is successful!");
} catch(IOException e) {
e.printStackTrace();
}
Input and output in the above example code need to be replaced with actual input flow and output stream.The Copy method will copy the content of the input stream to the output stream.
Summarize:
This article introduces how to use the Commons IO library for files and stream reading and writing operations.By importing dependencies, the method provided by FileUtils can easily read the content of the file and write the content into the file.In addition, the content of the input stream can be copied into the output stream through the COPY method.I hope this article will help you!