以下是一个在 Android 中使用多线程实现文件上传的示例代码:
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadUploader {
private static final String TAG = "MultiThreadUploader";
private static final int BUFFER_SIZE = 8192;
private String uploadUrl;
private File fileToUpload;
private int threadCount;
public MultiThreadUploader(String uploadUrl, File fileToUpload, int threadCount) {
this.uploadUrl = uploadUrl;
this.fileToUpload = fileToUpload;
this.threadCount = threadCount;
}
public void startUpload() {
try {
long fileLength = fileToUpload.length();
long partSize = fileLength / threadCount;
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
for (int i = 0; i < threadCount; i++) {
long start = i * partSize;
long end = (i == threadCount - 1)? fileLength - 1 : (i + 1) * partSize - 1;
UploadTask task = new UploadTask(start, end, i);
executor.execute(task);
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Upload completed.");
} catch (IOException e) {
Log.e(TAG, "Upload error: " + e.getMessage());
}
}
private class UploadTask implements Runnable {
private long start;
private long end;
private int taskId;
public UploadTask(long start, long end, int taskId) {
this.start = start;
this.end = end;
this.taskId = taskId;
}
@Override
public void run() {
try {
URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Range", "bytes " + start + "-" + end + "/" + fileToUpload.length());
OutputStream outputStream = connection.getOutputStream();
FileInputStream inputStream = new FileInputStream(fileToUpload);
inputStream.skip(start);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = inputStream.read(buffer))!= -1 && start <= end) {
outputStream.write(buffer, 0, bytesRead);
start += bytesRead;
}
inputStream.close();
outputStream.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Log.d(TAG, "Task " + taskId + " completed successfully.");
} else {
Log.e(TAG, "Task " + taskId + " failed with response code: " + responseCode);
}
} catch (IOException e) {
Log.e(TAG, "Task " + taskId + " error: " + e.getMessage());
}
}
}
public static void main(String[] args) {
String uploadUrl = "http://your-server-url.com/upload";
File fileToUpload = new File(Environment.getExternalStorageDirectory(), "your_file_to_upload.txt");
int threadCount = 3;
MultiThreadUploader uploader = new MultiThreadUploader(uploadUrl, fileToUpload, threadCount);
uploader.startUpload();
}
}
请注意:
- 这只是一个示例代码,在实际应用中,你可能需要处理更多的错误情况,如网络连接问题、服务器错误响应等。
- 在 Android 应用中,确保你有适当的权限来访问外部存储(如果文件在外部存储上)和进行网络操作。并且应该在主线程之外的线程中执行网络操作,以避免阻塞主线程。