网上关于web 下载服务器文件的实现方式很多 这里记录一下纯java实现方法
上代码
package testOne;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class testone {
public static void main(String[] args) throws MalformedURLException {
// 要确保下面这个下载地址可以正常访问
String urlPath = "http://192.168.1.1:88/test/test.txt";
// 下载文件保存位置
String filePath = "C:\\Users\\77025\\Desktop\\12345";
URL url = new URL(urlPath);
try {
downloadFile(url,filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadFile(URL theURL, String filePath) throws IOException {
File dirFile = new File(filePath);
//文件路径不存在时,自动创建目录
if(!dirFile.exists()){
dirFile.mkdir();
}
URLConnection connection = theURL.openConnection();
InputStream in = connection.getInputStream();
// test.txt 这里的text与下载文件名称最好一致
FileOutputStream os = new FileOutputStream(filePath+"\\test.txt");
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = in.read(buffer)) > 0) {
os.write(buffer, 0, read);
}
os.close();
in.close();
}
}
网友评论