如何下载文件并在本地获取路径位置

我有一个URL,即http://downloadplugins.verify.com/Windows/SubAngle.exe 。 如果我将其粘贴到选项卡上并按Enter键,则文件(SubAngle.exe)将被下载并保存在下载文件夹中。这是手动过程。但是可以使用java代码完成。 我用文件名即SubAngle.exe编写了获取绝对路径的代码。

要求: – 在下载URL文件的帮助下,validation文件是否已下载并返回文件的绝对路径。

where locfile is "http://downloadplugins.verify.com/Windows/SubAngle.exe" public String downloadAndVerifyFile(String locfile) { File fileLocation = new File(locfile); File fileLocation1 = new File(fileLocation.getName()); String fileLocationPath = null; if(fileLocation.exists()){ fileLocationPath = fileLocation1.getAbsolutePath(); } else{ throw new FileNotFoundException("File with name "+locFile+" may not exits at the location"); } return fileLocationPath; } 

从URL下载文件的代码

 import java.net.*; import java.io.*; public class DownloadFile { public static void main(String[] args) throws IOException { InputStream in = null; FileOutputStream out = null; try { // URL("http://downloadplugins.verify.com/Windows/SubAngle.exe"); System.out.println("Starting download"); long t1 = System.currentTimeMillis(); URL url = new URL(args[0]); // Open the input and out files for the streams HttpURLConnection conn = (HttpURLConnection) url.openConnection(); in = conn.getInputStream(); out = new FileOutputStream("YourFile.exe"); // Read data into buffer and then write to the output file byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } long t2 = System.currentTimeMillis(); System.out.println("Time for download & save file in millis:"+(t2-t1)); } catch (Exception e) { // Display or throw the error System.out.println("Erorr while execting the program: " + e.getMessage()); } finally { // Close the resources correctly if (in != null) { in.close(); } if (out != null) { out.close(); } } } } 

正确配置fileName的值以了解文件的存储位置。 资料来源: http : //www.devmanuals.com/tutorials/java/corejava/files/java-read-large-file-efficiently.html

修改源以使用http URL替换本地文件

输出:

java DownloadFile http://download.springsource.com/release/TOOLS/update/3.7.1.RELEASE/e4.5/springsource-tool-suite-3.7.1.RELEASE-e4.5.1-updatesite.zip

开始下载

以毫秒为单位下载和保存文件的时间:100184

而不是写这个巨大的代码,去Apache的commons.io试试这个:

 URL ipURL = new URL("inputURL"); File opFile = new File("outputFile"); FileUtils.copyURLToFile(ipURL, opFile);