Java是一種廣泛使用的編程語言,可以用于開發各種類型的應用程序,包括文件上傳和下載的功能。在Java中,可以使用HttpURLConnection類或Apache HttpClient庫來實現文件上傳和下載操作。
// 上傳文件 URL url = new URL("http://example.com/upload"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); File file = new File("path/to/file"); FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead = -1; OutputStream outputStream = conn.getOutputStream(); while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } inputStream.close(); outputStream.close(); // 下載文件 URL url = new URL("http://example.com/download/file.txt"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder content = new StringBuilder(); while ((inputLine = in.readLine()) != null) { content.append(inputLine); } in.close(); File file = new File("path/to/save/file.txt"); FileOutputStream outputStream = new FileOutputStream(file); outputStream.write(content.toString().getBytes()); outputStream.close();
以上代碼僅作為演示,實際應用中還需要加入文件名、文件類型等信息的處理,以及異常處理和安全性考慮。