java没有这样的文件或目录

我在一个java类,我不在servlet上

问题不重复,我不是在servlet上请大家。

通过java类,我的意思是:

class HelloWorld{} 

我在服务器上,我想允许客户端下载文件

这是我的代码:

 @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path("/downloadFile") public Response getFile() { File file = new File("/roma.txt"); System.out.println("path = " + file.getPath()); System.out.println("absoulte path = " + file.getAbsolutePath()); return Response .ok(file, MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"") // optional .build(); } 

该文件位于我的项目的WebContent ,如下所示: 在此处输入图像描述

我有这个例外:

 java.io.FileNotFoundException: /roma.txt (No such file or directory) 

尝试删除“/”,

 File file = new File("roma.txt"); 

“/roma.txt”可以指根目录。

这可以在Windows,Linux,Mac OSX中使用:

 File myFile = new File(System.getProperty("user.home"), "roma.txt"); 

然后“roma.txt”将放入当前用户的主目录。