文件上傳和下載是常見的網絡操作,Java可以通過使用Java API中的一些類來實現文件上傳和下載。
文件上傳: 可以使用Java的HttpURLConnection類來實現文件上傳。首先需要創建一個URL對象表示上傳的地址,然后通過HttpURLConnection對象打開連接,并設置請求方法為POST。接著需要設置一些請求頭信息,如Content-Type和Content-Disposition。最后將文件內容寫入輸出流中發送到服務器。以下是一個簡單的文件上傳示例:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUpload {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/upload");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
File file = new File("path/to/file.txt");
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);
}
fileInputStream.close();
outputStream.close();
int responseCode = connection.getResponseCode();
System.out.println("Server response code: " + responseCode);
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件下載: 可以使用Java的HttpURLConnection類來實現文件下載。首先需要創建一個URL對象表示下載的地址,然后通過HttpURLConnection對象打開連接,并設置請求方法為GET。接著可以設置一些請求頭信息,如User-Agent。最后讀取輸入流中的文件內容并保存到本地文件。以下是一個簡單的文件下載示例:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileDownload {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/file.txt");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("path/to/save/file.txt");
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
inputStream.close();
fileOutputStream.close();
int responseCode = connection.getResponseCode();
System.out.println("Server response code: " + responseCode);
} catch (IOException e) {
e.printStackTrace();
}
}
}
請注意,在實際開發中,需要根據具體的需求和服務器端的要求來設置請求頭信息和處理響應信息。