java获取templates下文件
时间: 2023-08-04 22:07:30 浏览: 56
你可以使用 Java 的资源加载器(ResourceLoader)来获取 templates 目录下的文件。下面是一个简单的示例代码:
```java
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
String fileName = "templates/example.txt"; // 文件路径
try {
// 使用资源加载器加载文件
Resource resource = new ClassPathResource(fileName);
byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
String content = new String(bytes, StandardCharsets.UTF_8);
System.out.println("文件内容: " + content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
上述代码中,我们使用了 Spring Framework 提供的资源加载器 `ResourceLoader`,将文件加载为字节数组,并将其转换为字符串。你可以将 `templates/example.txt` 替换为你具体的文件路径。注意,这里假设 `templates` 目录是在类路径(classpath)下。如果你没有使用 Spring Framework,你也可以使用其他方式来获取资源,比如使用 `ClassLoader` 加载类路径下的资源。