Java下载与上传代码详解
Java下载代码
在Java中,下载文件通常可以通过使用java.net.URL和java.io.InputStream来实现,以下是一个简单的示例,展示如何使用Java下载一个文件:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class FileDownloader {
public static void downloadFile(String fileURL, String saveDir) {
try {
// 创建URL对象
URL url = new URL(fileURL);
// 打开连接
InputStream in = new BufferedInputStream(url.openStream());
// 创建输出流
FileOutputStream fileOutputStream = new FileOutputStream(saveDir);
byte[] dataBuffer = new byte[1024];
int bytesRead;
// 读取数据到缓冲区
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
// 写入文件
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
// 关闭流
fileOutputStream.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String fileURL = "http://example.com/file.zip";
String saveDir = "/path/to/your/directory/file.zip";
downloadFile(fileURL, saveDir);
}
}
Java上传代码
上传文件到服务器通常需要使用HTTP POST请求,以下是一个使用Java实现文件上传的示例,使用了java.net.HttpURLConnection:

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void uploadFile(String targetUrl, File file) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(targetUrl);
// 打开连接
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置允许输出
connection.setDoOutput(true);
// 设置请求头
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("Content-Length", String.valueOf(file.length()));
// 获取输出流
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// 创建文件输入流
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
// 读取文件并写入输出流
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 关闭流
fileInputStream.close();
outputStream.flush();
outputStream.close();
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String targetUrl = "http://example.com/upload";
File file = new File("/path/to/your/file.txt");
uploadFile(targetUrl, file);
}
}
代码展示了如何在Java中下载和上传文件,下载代码使用了BufferedInputStream来读取数据,而上传代码则使用了DataOutputStream和FileInputStream来发送文件数据,这两个示例都是基本的实现,实际应用中可能需要根据具体需求进行调整和优化。



















