我正在尝试读取不同包中但在同一项目中可用的文本文件,但总是将 InputStream 设为 null。
public class ReadFileApp {
public static void main(String[] args) {
Thread currentThread = Thread.currentThread();
ClassLoader classLoader = currentThread.getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("/com/rpsoft/response/fileOneResponse.txt");
String response = null;
try {
response = new String(FileCopyUtils.copyToByteArray(inputStream));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Current Thread : " + currentThread);
System.out.println("Class Loader : " + classLoader);
System.out.println("InputStream : "+ inputStream);
System.out.println("Response : " + response);
}
}
获取异常:
Exception in thread "main" java.lang.IllegalArgumentException: No InputStream specified
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.util.FileCopyUtils.copy(FileCopyUtils.java:106)
at org.springframework.util.FileCopyUtils.copyToByteArray(FileCopyUtils.java:156)
at com.rpsoft.filetransport.ReadFileApp.main(ReadFileApp.java:18)
最佳答案
您可以根据项目中的文件位置尝试任何一种。
// Read from same package
getClass().getResourceAsStream("fileOneResponse.txt")
// Read from resources folder parallel to src in your project
new File("resources/fileOneResponse.txt")
// Read from src/resources folder
getClass().getResource("/resources/fileOneResponse.txt")
// Read from src/resources folder
getClass().getResourceAsStream("/resources/fileOneResponse.txt")
关于Java在eclipse中读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24269523/