gpt4 book ai didi

Java在eclipse中读取文本文件

转载 作者:行者123 更新时间:2023-12-01 12:50:17 27 4
gpt4 key购买 nike

我正在尝试读取不同包中但在同一项目中可用的文本文件,但总是将 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com