我想生成博客文章概述。为此,我想从Spring Boot存储其模板的资源文件夹中的templates文件夹内的文件夹中读取html文件。
我尝试过,但它没有返回错误,但也没有列出任何文件。
去这儿的方法是什么?
谢谢
@Controller
public class Route {
@Autowired
private ResourceLoader resourceLoader;
@RequestMapping("/")
public String home() throws IOException {
final String path = "templates/blog";
final Resource res = resourceLoader.getResource("templates/blog");
try (final BufferedReader reader = new BufferedReader(new InputStreamReader(res.getInputStream()))) {
reader.lines().forEachOrdered(System.out::println);
}
return "blog/a";
}
}
@Controller
public class Route {
@Value("classpath:templates/blog/*")
private Resource[] resources;
@RequestMapping("/")
public String home() throws IOException {
for (final Resource res : resources) {
System.out.println(res.getFilename());
}
return "blog/a";
}
}
对我有所帮助。
你应该能够使用NIO2实现这一目标。
为了使NIO2工作,它需要concept of FileSystem,并且可以从jar URI创建一个。然后,此文件系统可以与文件/路径一起使用。下面的代码包含两个分支 - 第一个句柄从Jar内部加载文件,第二个分支 - 当代码从IDE或"mvn spring-boot:run"
运行时。
所有流都通过try-with-resources使用,因此它们将自动关闭。
find函数从文件系统的顶部开始,递归搜索html文件。
public static void readFile(String location) throws URISyntaxException {
URI uri = Objects.requireNonNull(ReadFromJar.class.getClassLoader().getResource(location)).toURI();
if (uri.getScheme().equals("jar")) { //inside jar
try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) { //build a new FS that represents the jar's contents
Files.find(fs.getPath("/"), 10, (path, fileAttr) -> // control the search depth (e.g. 10)
fileAttr.isRegularFile() //match only files
&& path.toString().contains("blog") //match only files in paths containing "blog"
&& path.getFileName().toString().matches(".*\\.html")) // match only html files
.forEach(ReadFromJar::printFileContent);
} catch (IOException ex) {
ex.printStackTrace();
}
}
else { //from IDE or spring-boot:run
final Path path = Paths.get(uri);
try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(path)) {
dirStream.forEach(ReadFromJar::printFileContent);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void printFileContent(final Path file) {
try {
System.out.println("Full path: " + file.toAbsolutePath().toString());
Files.lines(file).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}