gpt4 book ai didi

java - 在 Spring 的构造函数参数中从类路径读取文件时出现 FileNotFound 异常

转载 作者:行者123 更新时间:2023-12-02 06:09:56 30 4
gpt4 key购买 nike

我在以下位置有一个文件 mydoc.txt

C:/Tomcat6.0/webapps/myapp/WEB-INF/classes/document/mydoc.txt

我必须通过构造函数注入(inject)获取此文件位置并读取该文件。

public DocumentReader(String path) throws IOException, FileNotFoundException {
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
String doc = stringBuilder.toString();
}

我已在 applicationContext.xml 中配置了文件位置,如下所示。

<bean id="DocumentReader" class="com.myapp.DocumentReader" >
<constructor-arg value="classpath:document/mydoc.txt"></constructor-arg>
</bean>

但是,我在运行应用程序时遇到 FileNotFound 异常。有没有其他方法可以从此位置读取文件?

异常

java.io.FileNotFoundException:  classpath:document\mydoc.txt(The filename, directory name, or volume label syntax is incorrect)

最佳答案

更改构造函数以采用 org.springframework.core.io.Resource 而不是 String。

如果您的构造函数参数是 String 类型,Spring 会按照您写下来的方式插入该值。然后,您的 FileReader 在 classpath:document 文件夹中查找名为 mydoc.txt 的文件(在某些操作系统(如 Windows)上,该文件甚至不是有效的文件夹名称)

如果你的构造函数参数是Ressource类型,Spring会假设你注入(inject)的字符串是一个Spring-Ressource-Path,并为你解析它。

关于java - 在 Spring 的构造函数参数中从类路径读取文件时出现 FileNotFound 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21982564/

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