我在 Spring MVC 项目的资源中创建了文本文件,并尝试在 Controller 中访问它以读取内容。但它给了我未找到异常。
//ClassLoader classLoader = getClass().getClassLoader();
//File file = new File(classLoader.getResource("path.txt").getFile());
String fp=new File("").getAbsolutePath(); //Absolute path returns the ecplise location and not the project or workspace location
// File f=ResourceUtils.getFile("classpath:path.txt");
// File f = new File(getClass().getResource("path.txt").getFile());
// File f = new ClassPathResource("path.txt").getFile();
// InputStream in = new FileInputStream(f);
// BufferedReader br=new BufferedReader(new FileReader(fp+File.separator+"/path.txt"));
最佳答案
摘自@NimChimpsky 在 similar question: 中的回答
Resource resource = new ClassPathResource("path.txt");
InputStream resourceInputStream = resource.getInputStream();
使用ClassPathResource和接口(interface)Resource 。并确保您正确添加资源目录(将 /src/main/resources/
添加到类路径中)。
请注意,Resource 有一个获取 java.io.File
的方法,因此您也可以使用:
Resource resource = new ClassPathResource("path.txt");
FileReader fr = new FileReader(resource.getFile());
关于java - Spring MVC 无法从 Controller 中的资源访问文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52245380/