官术网_书友最值得收藏!

Commons IO

Like Apache Commons Lang extends the java.util standard package, Apache Commons IO extends java.io; it is a Java library of utilities to assist with I/O in Java, which, as we previously learned, can be quite verbose.

To include the library in your project, add the dependency snippet to the pom.xml file:

<dependency> 
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>

We already learned about Files.lines from Java NIO. While it is handy, we do not always work with files, and sometimes need to get lines from some other InputStream, for example, a web page or a web socket.

For this purpose, Commons IO provides a very helpful utility class IOUtils. Using it, reading the entire input stream into string or a list of strings is quite easy:

try (InputStream is = new FileInputStream("data/text.txt")) { 
String content = IOUtils.toString(is, StandardCharsets.UTF_8);
System.out.println(content);
}

try (InputStream is = new FileInputStream("data/text.txt")) {
List<String> lines = IOUtils.readLines(is, StandardCharsets.UTF_8);
System.out.println(lines);
}

Although we use FileInputStream objects in this example, it can be any other stream. The first method, IOUtils.toString, is particularly useful, and we will use it later for crawling web pages and processing the responses from web services.

There are a lot more useful methods for I/O in this library, and to get a good overview, you can consult the documentation available at https://commons.apache.org/io.

主站蜘蛛池模板: 昭平县| 亚东县| 女性| 镇雄县| 漯河市| 富平县| 定州市| 广东省| 尚志市| 通江县| 邯郸市| 鄂托克前旗| 七台河市| 醴陵市| 和林格尔县| 景洪市| 平舆县| 广宗县| 同德县| 卢氏县| 沐川县| 南皮县| 安塞县| 金门县| 同德县| 德昌县| 同德县| 张家川| 萝北县| 德安县| 凉山| 闵行区| 凌云县| 顺平县| 阿勒泰市| 奉贤区| 历史| 临泉县| 本溪市| 洛浦县| 甘谷县|