java没有这样的文件或目录

java没有这样的文件或目录

问题描述:

我在java类上,我不在servlet上

问题不重复,我不在servlet上拜托。

the question is not duplicated, i am not on a servlet please guys.

和java类,我的意思是:

and by a java class, i mean:

class HelloWorld{}

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

I am on server, and I want to allow the client to download a file

这是我的代码:

@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 如您所见:

the file is located in the WebContent of my project as you see here:

我得到了这个例外:

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


尝试删除/,

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

/ roma.txt可以指根目录。

"/roma.txt" may refer to root directory.

这适用于Windows,Linux,Mac OSX:

This could work in Windows , Linux , Mac OSX :

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

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

and then "roma.txt" would put into home dir of current user.