我有以下问题。我必须从服务器下载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();
}我还尝试在fileUrl中通过"%20“替换空格。那么问题会是什么呢?正如我在上面写的,没有任何空格的文件可以在下载后打开,没有任何问题。
我使用的是Java1.7。
干杯,
安德烈
发布于 2016-11-07 20:51:52
如果fileName包含空格,则将其替换为其他字符。这可能行得通,如果不行,请让我知道。
if(fileName.trim().contains(" "))
fileName.replace(" ","_");发布于 2016-11-07 21:43:09
URL url = new URL(URLEncoder.encode(fileUrl, "UTF-8"));
https://stackoverflow.com/questions/40465530
复制相似问题