阅读量:0
文件上传和下载是常见的网络操作,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(); } } }
请注意,在实际开发中,需要根据具体的需求和服务器端的要求来设置请求头信息和处理响应信息。