【问题标题】:Java FileNotFoundException when attempting to pass a text file to a POST and converting contents to a List<Integer>尝试将文本文件传递给 POST 并将内容转换为 List<Integer> 时出现 Java FileNotFoundException
【发布时间】: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


【解决方案1】:

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

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

因此,您可以查看当前在哪里寻找所述文件并从那里进行调整。

【讨论】:

  • 堆栈跟踪现在包括/Applications/Eclipse.app/Contents/MacOS/fileTesttxt
  • 这会告诉您应用程序当前在哪里寻找您的文件
  • 将文件放入目录后,调用服务时仍然出现相同的异常。
  • 是真正以“fileTesttxt”形式出现的字符串,因为如果是,您肯定需要它是“fileTest.txt”
  • 没有。它是文件测试.txt。那是一个错字。
【解决方案2】:

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

我将文件放在该目录中,并将绝对路径作为消息正文传递。如果你这样做,请确保你转义你的正斜杠!服务消息正文中使用的绝对路径如下所示:

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

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多