Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Java web处理程序中使用获取本地文件大小?_Java - Fatal编程技术网

如何在Java web处理程序中使用获取本地文件大小?

如何在Java web处理程序中使用获取本地文件大小?,java,Java,如何在web处理程序中获取本地文件长度 @RequestMapping(value = "xxx.iso", method = { RequestMethod.HEAD }) public void doChunkedHEAD(HttpServletResponse response) { try { URL fileUrl = servletContext.getResource(filename); File fileObj = new File(f

如何在web处理程序中获取本地文件长度

@RequestMapping(value = "xxx.iso", method = { RequestMethod.HEAD })
public void doChunkedHEAD(HttpServletResponse response) {

    try {
        URL fileUrl = servletContext.getResource(filename);
        File fileObj = new File(fileUrl.toString());
        long fileSize = fileObj.length();
        response.setHeader("Content-Length", String.valueOf(fileSize));

    } catch (Exception e) {

    }
}
文件大小始终为0。
fileUrl
是这样的:

file:/C:/xxx.iso
fileObj.exists()
返回
false
。但是该文件确实以
C:\xxx.iso
的形式存在

如果使用绝对局部路径,则可以获得大小:

@RequestMapping(value = "xxx.iso", method = { RequestMethod.HEAD })
public void doChunkedHEAD(HttpServletResponse response) {
    File fileObj = new File("C:\\xxx.iso");
    long fileSize = fileObj.length();
    response.setHeader("Content-Length", String.valueOf(fileSize));
}   
为什么?


我使用的是Java 1.7.76。

我使用了以下代码:

@RequestMapping(value = "xxx.iso", method = { RequestMethod.HEAD })
public void doChunkedHEAD(HttpServletResponse response) {

    try {
        String localAppRootPath = servletContext.getRealPath("/");
        Path filePath = Paths.get(localAppRootPath, "xxx.iso");
        File fileObj = new File(filePath.toString());
        long fileSize = fileObj.length();
        response.setHeader("Content-Length", String.valueOf(fileSize));
    } catch (Exception e) {

    }
}

但是我仍然不知道为什么我不能使用
URL

我用下面的代码做到了:

@RequestMapping(value = "xxx.iso", method = { RequestMethod.HEAD })
public void doChunkedHEAD(HttpServletResponse response) {

    try {
        String localAppRootPath = servletContext.getRealPath("/");
        Path filePath = Paths.get(localAppRootPath, "xxx.iso");
        File fileObj = new File(filePath.toString());
        long fileSize = fileObj.length();
        response.setHeader("Content-Length", String.valueOf(fileSize));
    } catch (Exception e) {

    }
}
但是我仍然不知道为什么我不能使用
URL