在Java中,可以使用Java IO或Java NIO来实现文件的上传与下载。
文件上传:
文件下载:
以下是一个示例代码,演示了如何使用Java IO实现文件的上传和下载:
文件上传示例:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) throws IOException {
String fileUrl = "http://example.com/upload"; // 文件上传的URL
String filePath = "path/to/file.txt"; // 要上传的文件路径
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream outputStream = connection.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
fileInputStream.close();
int responseCode = connection.getResponseCode();
System.out.println("Response Code:" + responseCode);
}
}
文件下载示例:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownloader {
public static void main(String[] args) throws IOException {
String fileUrl = "http://example.com/download/file.txt"; // 文件下载的URL
String savePath = "path/to/save/file.txt"; // 下载文件保存的路径
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
inputStream.close();
System.out.println("File downloaded successfully.");
} else {
System.out.println("File download failed. Response Code:" + responseCode);
}
}
}
这些示例代码使用了Java的标准库来进行文件的上传和下载操作。实际应用中,你可能需要根据具体需求进行适当的改进和优化。