需要从java中的URL下载.csv文件,但我得到的是.html源代码

时间:2017-03-14 09:59:36

标签: java html csv url nio

我正在编写一个程序,每次执行时都需要下载.csv文件以保持自己的最新状态。我正在使用NIO和以下代码下载:

URL url = new URL(urlStr);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();

问题是,我没有获取.csv内容,而是获得了带有URL的.html页面源代码的.csv。如果将URL与浏览器一起使用,则会下载正确的文件,但不会使用NIO。有没有办法强制程序获取文件而不是html内容?

编辑:尝试使用HttpURLConnection,bur得到相同的结果:

public static void downloadFile(String fileURL, String saveDir) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();
        int BUFFER_SIZE = 4096;

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {         
            // opens input stream from the HTTP connection
            InputStream inputStream = httpConn.getInputStream();

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

            int bytesRead = -1;

            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.close();
            inputStream.close();
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }

(改编自:http://www.codejava.net/java-se/networking/use-httpurlconnection-to-download-file-from-an-http-url

1 个答案:

答案 0 :(得分:-1)

private void download()
{
    WebClient webClient = new WebClient();                                                          // Creates a webclient
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);                   // Uses the Event Handler to check whether the download is complete
    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);  // Uses the Event Handler to check for progress made
    webClient.DownloadFileAsync(new Uri("URLpath"), @"destinationpath");           // Defines the URL and destination directory for the downloaded file
}

试试这个