从java中的url下载文件不完整 - 使用java NIO

时间:2013-12-12 10:23:45

标签: java

我使用下面线程的公认解决方案中提供的代码下载500kb的zip文件 How to download and save a file from Internet using Java?

public static File  downloadFile(String fileURL, String saveDir)
        throws IOException {

    File downloadFolder = null;
    String saveFilePath = null;

    URL url = new URL(fileURL);
   ReadableByteChannel rbc = Channels.newChannel(url.openStream());
   String    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); 
   FileOutputStream fos = new FileOutputStream(fileName);

   saveFilePath = saveDir + File.separator + fileName;
   downloadFolder = new File(saveDir);

   downloadFolder.deleteOnExit();
   downloadFolder.mkdirs();

   FileOutputStream outputStream = new FileOutputStream(saveFilePath);
   outputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

   outputStream.close();
  rbc.close();
    return new File(saveFilePath);
}

代码能够识别文件,但问题是,下载不完整。它总是下载5KB并在之后停止。

我不想使用apache commons文件直到。

1 个答案:

答案 0 :(得分:0)

问题是我没有设置身份验证。我设置了身份验证,它工作正常。代码

public static File  downloadFile(String fileURL, String saveDir)
    throws IOException {

File downloadFolder = null;
String saveFilePath = null;

String username = "guest";
String password = "guest";

String usepass = username + ":" + password;
String basicAuth = "Basic "+  javax.xml.bind.DatatypeConverter.printBase64Binary(usepass.getBytes());

URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) website.openConnection();
httpConn.setRequestProperty("Authorization", basicAuth);

ReadableByteChannel rbc = Channels.newChannel(httpConn.getInputStream());
String    fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,fileURL.length()); 
FileOutputStream fos = new FileOutputStream(fileName);

saveFilePath = saveDir + File.separator + fileName;
downloadFolder = new File(saveDir);

downloadFolder.deleteOnExit();
downloadFolder.mkdirs();

FileOutputStream outputStream = new FileOutputStream(saveFilePath);
outputStream.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

outputStream.close();
rbc.close();
return new File(saveFilePath);

}