用java编写一个上传下载代码示例

下面是一个用 Java 编写的上传文件的示例代码:

import java.io.*;
import java.net.*;
import java.util.*;

public class FileUpload {
  public static void main(String[] args) throws Exception {
    String fileName = "test.txt";
    String urlString = "http://www.example.com/upload";

    // Create a URL object
    URL url = new URL(urlString);

    // Open a connection to the URL
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Set the request method to "POST"
    connection.setRequestMethod("POST");

    // Set the request properties
    connection.setRequestProperty("Content-Type", "multipart/form-data");
    connection.setRequestProperty("Content-Length", String.valueOf(new File(fileName).length()));

    // Enable output
    connection.setDoOutput(true);

    // Open a output stream to the server
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

    // Open an input stream to the file
    FileInputStream inputStream = new FileInputStream(fileName);

    // Read the contents of the file into a byte array
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
      // Write the bytes to the output stream
      outputStream.write(buffer, 0, bytesRead);
    }

    // Close the input and output streams
    inputStream.close();
    outputStream.close();

    // Get the response code from the server
    int responseCode = connection.getResponseCode();
    System.out.println("Response code: " + responseCode);

    // Read the response from the server
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    reader.close();
  }
}

下面是一个用 Java 编写的下载文件的示例代码:

``` import java.io.; import java.net.;

public class FileDownload { public static void main(String[] args) throws Exception { String fileUrl = "http://www.example.com/download/test.txt"; String fileName = "test.txt";

// Open a connection to the URL
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Set the request method to "GET"
connection.setRequestMethod("GET");

// Open an input stream to the file
InputStream inputStream = connection.getInputStream();

// Create a file output stream
FileOutputStream outputStream = new FileOutputStream(fileName);

// Read the contents of the file into a byte array
byte[] buffer = new byte[1024];
int
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值