一、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文件里引入依赖:
commons-io
commons-io
2.4
演示代码如下:
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文件里引入依赖:
com.google.guava
guava
28.1-jre
演示代码如下:
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();
}
}
}