Java 在路径“上找不到文件”&引用;src/test/resources/“;
我的java测试代码尝试访问项目文件夹中的文件 但我得到一个例外:Java 在路径“上找不到文件”&引用;src/test/resources/“;,java,file,unit-testing,io,Java,File,Unit Testing,Io,我的java测试代码尝试访问项目文件夹中的文件 但我得到一个例外: String fileContents = new String(Files.readAllBytes( Paths.get("src/test/resources/SenegalAndBulgariaConfig.txt"))); String fileContents = new String(Files.readAllBytes( Paths.get("src
String fileContents = new String(Files.readAllBytes(
Paths.get("src/test/resources/SenegalAndBulgariaConfig.txt")));
String fileContents = new String(Files.readAllBytes(
Paths.get("src/")));
它过去可以工作,但现在不行了:
java.nio.file.NoSuchFileException: src/test/resources/SenegalAndBulgariaConfig.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.Files.readAllBytes(Files.java:3152)
尽管它存在:
我认为您应该从fileContents字符串中删除“src”。您永远不应该依赖
文件。从类路径加载InputStream
如果使用Maven标准目录结构,则src/main/resources和src/test/resources都位于类路径中
我倾向于喜欢Apache Commons IO库和SpringClassPathResource
将文件作为资源加载(通过类路径)或直接在驱动器上寻址,两者之间常常存在混淆。也许我的回答可以帮助您区分两者。假设SenegalAndBulgariaConfig.txt
位于/resources
:
InputStream is = getClass().getResourceAsStream("/SenegalAndBulgariaConfig.txt");
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, Charset.defaultCharset());
String fileContents = writer.toString();
System.out.println(fileContents );
注意getClass()
可以替换为ClassName.class
private String readFileContent(String filePath) throws URISyntaxException, IOException {
byte[] bytes = Files.readAllBytes(Paths.get(getClass().getClassLoader().getResource(filePath).toURI()));
return new String(bytes);
}
在您的情况下,文件路径将是SenegalAndBulgariaConfig.txt
例如:
String senegalAndBulgariaConfig = readFileContent("SenegalAndBulgariaConfig.txt");
文件确实存在于该位置吗?您不能依赖文件系统。您需要从类路径将文件作为资源加载。这是spring项目吗?@TwiN gradle Projects非常确定您需要的是绝对路径,而不仅仅是从src
加载。快速查看一下这个代码,我得到了这个代码的NPE:`String fileContents=IOUtils.toString(getClass().getClassLoader().getResourceAsStream(“src/test/resources/SenegalAndBulgariaConfig.txt”)`我想我已经解释过src/test/resources在类路径中。把它拿出来,剩下的留着。应该是“SenegalAndBulgariaConfig.txt”。在尝试读取之前,您不想确保返回的输入流不为null吗?我同意所有(+1),但我们可以在没有Apache Commons IO库和Spring的情况下很好地完成任务。为什么“src/”下的任何内容都应该在类路径中?IOUTIL来自哪里?Apache Commons IO