javaでファイルをクラウドサーバーにアップロードする方法

ファイルをクラウドコンピューティングサービスにアップロードするには、Javaのソケットプログラミングが使用できます。以下に簡単なコード例を示します。

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class FileUploader {
public static void main(String[] args) {
String host = "云主机IP地址";
int port = 12345;
String filePath = "要上传的文件路径";
File file = new File(filePath);
try (Socket socket = new Socket(host, port);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
// 发送文件名和文件大小
out.write((file.getName() + "\n").getBytes());
out.flush();
out.write((file.length() + "\n").getBytes());
out.flush();
// 上传文件内容
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
out.flush();
}
System.out.println("文件上传成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}

実際のサーバーIPアドレスとアップロードファイルのパスにそれぞれ置き換えてください。

ソケットを使用してクラウドホストに接続し、ファイル名とファイルサイズを送信し、その後ファイル内容をブロック単位で読み取ってクラウドホストに送信することでファイルアップロード操作を完了します。

bannerAds