我寻找一些使用Java下载文件并将其移动到不同目录的脚本或教程,但是我看到很多类似于我的问题都得到了回答,但它们都有所不同。是否有明确的方法来实现这个?我目前正在学习Java,并没有足够的经验来制作这样的脚本。有谁可以帮忙吗?
我认为这是从网络上下载文件的最佳方法。当你下载文件时,它会被存储在当前正在运行的程序中,除非你特别指定将其存储在硬盘上。
URL url;
URLConnection con;
DataInputStream dis;
FileOutputStream fos;
byte[] fileData;
try {
url = new URL("http://website.com/file.pdf"); //File Location goes here
con = url.openConnection(); // open the url connection.
dis = new DataInputStream(con.getInputStream());
fileData = new byte[con.getContentLength()];
for (int q = 0; q < fileData.length; q++) {
fileData[q] = dis.readByte();
}
dis.close(); // close the data input stream
fos = new FileOutputStream(new File("/Users/kfang/Documents/Download/file.pdf")); //FILE Save Location goes here
fos.write(fileData); // write out the file we want to save.
fos.close(); // close the output stream writer
}
catch(Exception m) {
System.out.println(m);
}