Java是一種非常強(qiáng)大的編程語(yǔ)言,可以輕松實(shí)現(xiàn)各種功能。其中一個(gè)非常常見(jiàn)的功能就是上傳和下載文件。下面我們就來(lái)介紹一下Java如何實(shí)現(xiàn)上傳和下載。
上傳文件
public void uploadFile(String url, String filePath) { try { URL uploadUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) uploadUrl.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 = -1; 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); } catch (Exception e) { e.printStackTrace(); } }
下載文件
public void downloadFile(String url, String saveFilePath) { try { URL downloadUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead = -1; File file = new File(saveFilePath); FileOutputStream fileOutputStream = new FileOutputStream(file); while ((bytesRead = inputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, bytesRead); } fileOutputStream.close(); inputStream.close(); System.out.println("File downloaded: " + saveFilePath); } else { System.out.println("Download failed"); } } catch (Exception e) { e.printStackTrace(); } }
以上就是Java實(shí)現(xiàn)上傳和下載的基本代碼示例。當(dāng)然在實(shí)際開(kāi)發(fā)中,還需要考慮一些其他的情況,例如上傳文件大小、下載進(jìn)度顯示等等。希望這篇文章能夠幫助到需要實(shí)現(xiàn)上傳和下載功能的開(kāi)發(fā)者們。