一、InputStream类中read方法
package com.zhiyin.test;
import java.io.InputStream;
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
myTest.test();
}
public void test() {
try {
// 读取测试文件
MyTest test = new MyTest();
InputStream is = test.getClass().getResourceAsStream("testFile.txt");
byte[] byteArr = new byte[is.available()];
is.read(byteArr);
String str = new String(byteArr);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
二、开源工具类IOUtils中toString方法
maven项目中pom.xml文件里引入依赖:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
演示代码如下:
package com.zhiyin.test;
import org.apache.commons.io.IOUtils;
import java.io.InputStream;
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
myTest.test();
}
public void test() {
try {
// 读取测试文件
MyTest test = new MyTest();
InputStream is = test.getClass().getResourceAsStream("testFile.txt");
String str = IOUtils.toString(is);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}
三、开源工具类CharStreams中toString方法
maven项目中pom.xml文件里引入依赖:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
演示代码如下:
package com.zhiyin.test;
import com.google.common.io.CharStreams;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MyTest {
public static void main(String[] args) {
MyTest myTest = new MyTest();
myTest.test();
}
public void test() {
try {
// 读取测试文件
MyTest test = new MyTest();
InputStream is = test.getClass().getResourceAsStream("testFile.txt");
// 字节输入流转字符输入流
InputStreamReader isr = new InputStreamReader(is);
// CharStreams.toString()方法转换字符输入流
String str = CharStreams.toString(isr);
System.out.println(str);
} catch (Exception e) {
e.printStackTrace();
}
}
}