Java 尝试将文本文件传递给 POST 并将内容转换为列表时出现 FileNotFoundException<Integer>

Java FileNotFoundException when attempting to pass a text file to a POST and converting contents to a List<Integer>

我正在使用 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: 

尝试在端点的开头添加它。

System.out.println(new File( fileName).getAbsolutePath());

因此您可以看到您当前正在寻找所述文件的位置并从那里进行调整。

基于 RobOhRob 的回答,我明白了。一旦我在方法的开头使用 System.out.println(new File( fileName).getAbsolutePath()); 命中服务,它就会将绝对路径记录为 /Applications/Eclipse.app/Contents/MacOS/fileTest.txt.

我把文件放在那个目录下,并通过绝对路径作为消息正文。如果你这样做,请确保你转义了你的正向斜线!服务消息正文中使用的绝对路径如下所示:

//Applications//Eclipse.app//Contents//MacOS//fileTest.txt