[英]Can't access file in Java resources folder from Tomcat server
I'm struggling to get my simple Tomcat app to work.我正在努力让我的简单 Tomcat 应用程序正常工作。
I have csv file placed in src/main/resources/cities.csv我有 csv 文件放在 src/main/resources/cities.csv
and in my test main method everything goes well.在我的测试主要方法中,一切顺利。 However when I refer to this using a method in servlet I get: java.nio.file.NoSuchFileException但是,当我使用 servlet 中的方法引用它时,我得到:java.nio.file.NoSuchFileException
FileOperations:文件操作:
public class FileOparations {
static private final Path path = Paths.get("src/main/resources/cities.csv");
public static List<City> getCitiesList() {
return getCitiesStream().collect(Collectors.toList());
}
public static Stream<City> getCitiesStream() {
try {
return Files.readAllLines(path)
.stream()
.skip(1)
.map((String line) -> {
return line.split("\",\"");
})
.map((String[] line) -> {
String[] newData = new String[line.length];
for (int i = 0; i < line.length; i++) {
newData[i] = line[i].replaceAll("\"", "");
}
return newData;
})
.map((String[] data) -> {
String name = data[0];
String nameAscii = data[1];
String gps = data[2] + ":" + data[3];
String country = data[4];
String adminName = data[7];
String capitol = data[8];
long population;
try {
population = Long.parseLong(data[9]);
} catch (NumberFormatException e) {
population = Integer.MIN_VALUE;
}
int id = Integer.parseInt(data[10]);
return new City(name, nameAscii, id, country, gps, capitol, population, adminName);
});
} catch (IOException e) {
e.printStackTrace();
}
return Stream.empty();
}
My code in servlet looks like this:我在 servlet 中的代码如下所示:
protected void doGet(HttpServletRequest request, HttpServletResponse response){
List<City> cities = FileOparations.getCitiesList();
request.setAttribute("cities", cities);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
I'm surprised, because I'm not passing any URL through servlet, I want to call static method from Java. Method getCitiesList calls stream, mapping and returns ready to use list.我很惊讶,因为我没有通过 servlet 传递任何 URL,我想从 Java 调用 static 方法。方法 getCitiesList 调用 stream,映射并返回准备使用列表。
Try using getServletContext() :尝试使用getServletContext() :
String relativePath = "/resources/cities.csv";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
Relative path will be the path from the directory, expanded from the WAR file in your tomcat. So before building, it should be in src/main/webapp/相对路径将是目录的路径,从您的 tomcat 中的 WAR 文件展开。因此在构建之前,它应该在 src/main/webapp/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.