路径中包含空格的已下载文件已损坏

时间:2016-11-07 12:44:38

标签: java

我有以下问题。我必须从服务器下载pdf文件,其中一些文件名称中有空格。因此,每个文件都将被下载,但那些具有空格的文件无法打开。

如果我通过chrome访问服务器上的这些文件,它们会打开(也可以使用url中的空格)。

我想知道的是,java说文件将被下载。但是当我尝试在Acrobat Reader中打开它们时,它会向我显示一条错误消息,即文件已损坏。以下是我的代码示例:

public static void downloadFile(String fileURL, String saveDir) throws IOException {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {          
            return new PasswordAuthentication("*****", "*********".toCharArray());
        }
    });

    final int BUFFER_SIZE = 4096;
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    String credentials = "ptt" + ":" + "ptt123";
    String encoding = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
    httpConn.setRequestProperty("Authorization", String.format("Basic %s", encoding));
    int responseCode = 0;
    responseCode = httpConn.getResponseCode();
    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10,
                        disposition.length() - 1);
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
            fileURL.length());
        }



        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();
        String saveFilePath = saveDir + File.separator + fileName;

        // opens an output stream to save into file
        FileOutputStream outputStream = new FileOutputStream(saveFilePath);

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.close();
        inputStream.close();

        System.out.println("File downloaded");
    } else {
        System.out.println("No file to download. Server replied HTTP code: " + responseCode);
    }
    httpConn.disconnect();
}

我还尝试通过"%20"来替换空格。在fileUrl中。 那可能是什么问题呢?正如我上面所写,下载后没有任何空格的文件可以毫无问题地打开。

我使用Java 1.7。

干杯,

的Andrej

2 个答案:

答案 0 :(得分:0)

如果fileName包含空格,则将其替换为其他charecter。它可能有用,如果没有,请告诉我。

{
    "myId": {
    "type": "string", 
    "id": true 
  }
}

答案 1 :(得分:0)

URL url = new URL(URLEncoder.encode(fileUrl, "UTF-8"));