在Java中實現文件上傳和下載功能可以使用Java的文件操作類和網絡編程類來實現。下面是一個簡單的示例代碼:
文件上傳功能:
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileUploader {
public static void main(String[] args) {
String fileToUpload = "path/to/file.txt";
String uploadUrl = "http://example.com/upload";
try {
// 創建URL對象
URL url = new URL(uploadUrl);
// 創建連接對象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設置請求方法為POST
connection.setRequestMethod("POST");
// 允許輸入輸出流
connection.setDoInput(true);
connection.setDoOutput(true);
// 創建數據輸出流
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// 讀取文件內容并寫入輸出流
Path path = Paths.get(fileToUpload);
byte[] fileContent = Files.readAllBytes(path);
outputStream.write(fileContent);
// 關閉輸出流
outputStream.flush();
outputStream.close();
// 獲取響應碼
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 關閉連接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件下載功能:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileDownloader {
public static void main(String[] args) {
String downloadUrl = "http://example.com/file.txt";
String savePath = "path/to/save/file.txt";
try {
// 創建URL對象
URL url = new URL(downloadUrl);
// 創建連接對象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 獲取輸入流
InputStream inputStream = connection.getInputStream();
// 創建文件輸出流
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
// 讀取輸入流內容并寫入文件輸出流
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
// 關閉流
inputStream.close();
fileOutputStream.close();
connection.disconnect();
System.out.println("File downloaded successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代碼中的fileToUpload
和downloadUrl
分別是要上傳和下載的文件的路徑或URL。在實際使用時,需要將它們替換為實際的文件路徑或URL。同時,還需要注意文件路徑的正確性和訪問權限。