【发布时间】:2019-02-27 18:37:24
【问题描述】:
我正在使用 Java 8 和 Apache HttpClient 创建一个 RESTful Web 服务,它将文件名作为消息体传递。我正在尝试解析文本文件中的数据并将其添加到列表中。一切似乎都正常,除了我得到:Error Parsing: java.io.FileNotFoundException: testFile.txt (No such file or directory)。
这是服务端点代码:
@POST
@Path("/fileUpload")
@Consumes(MediaType.TEXT_PLAIN)
public Response fileUpload(String fileName) {
StringBuilder builder = new StringBuilder();
try {
List<String> items = new ArrayList<String>();
Scanner sc = new Scanner(new File(fileName));
while (sc.hasNext()) {
String line = sc.nextLine();
System.out.println(line);
items = Arrays.asList(line.split("\n"));
}
List<Integer> itemNbrs = new ArrayList<>();
for (String string : items) {
itemNbrs.add(Integer.valueOf(string));
}
sc.close();
itemNbrs.forEach(System.out::println);
// processImpl.checkItemsAndInsertIntoTable(itemNbrs);
} catch (Exception e) {
System.out.println("Error Parsing: " + e);
}
System.out.println("Data Received: " + builder.toString());
// return HTTP response 200 in case of success
return Response.status(200).entity(builder.toString()).build();
}
测试文件:
123
2345
4567
74543
9875
我试图将文件名作为 InputStream 传递,但我得到了同样的异常。我还使用chmod 777更改了测试文件的权限。
堆栈跟踪:
Error Parsing: java.io.FileNotFoundException: fileTest.txt
(No such file or directory)
Data Received:
【问题讨论】:
-
您是否将绝对路径传递给文件?
-
我已经发布了堆栈跟踪。 @Ruslan我尝试将文件放在它自己的目录中,并使用正确转义的反斜杠传递绝对路径。示例:
//Documents//Test//fileTest.txt。目前我只是传递文件名,该文件位于我项目的根目录中。 -
服务返回 200,代码在从 POST 方法中移除时有效。
标签: java rest web-services post http-post