以下是一个 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.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadBatchUploader {
private static final String TAG = "MultiThreadBatchUploader";
private static final int BUFFER_SIZE = 8192;
private String uploadUrl;
private List<File> filesToUpload;
private int threadCount;
public MultiThreadBatchUploader(String uploadUrl, List<File> filesToUpload, int threadCount) {
this.uploadUrl = uploadUrl;
this.filesToUpload = filesToUpload;
this.threadCount = threadCount;
}
public void startUpload() {
try {
List<UploadTask> tasks = new ArrayList<>();
for (int i = 0; i < filesToUpload.size(); i++) {
File file = filesToUpload.get(i);
long fileLength = file.length();
long partSize = fileLength / threadCount;
for (int j = 0; j < threadCount; j++) {
long start = j * partSize;
long end = (j == threadCount - 1)? fileLength - 1 : (j + 1) * partSize - 1;
UploadTask task = new UploadTask(start, end, file, i, j);
tasks.add(task);
}
}
ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
for (UploadTask task : tasks) {
executor.execute(task);
}
executor.shutdown();
while (!executor.isTerminated()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Batch upload completed.");
} catch (IOException e) {
Log.e(TAG, "Upload error: " + e.getMessage());
}
}
private class UploadTask implements Runnable {
private long start;
private long end;
private File file;
private int fileIndex;
private int taskId;
public UploadTask(long start, long end, File file, int fileIndex, int taskId) {
this.start = start;
this.end = end;
this.file = file;
this.fileIndex = fileIndex;
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 + "/" + file.length());
OutputStream outputStream = connection.getOutputStream();
FileInputStream inputStream = new FileInputStream(file);
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, "File " + fileIndex + ", Task " + taskId + " completed successfully.");
} else {
Log.e(TAG, "File " + fileIndex + ", Task " + taskId + " failed with response code: " + responseCode);
}
} catch (IOException e) {
Log.e(TAG, "File " + fileIndex + ", Task " + taskId + " error: " + e.getMessage());
}
}
}
public static void main(String[] args) {
String uploadUrl = "http://your-server-url.com/upload";
List<File> filesToUpload = new ArrayList<>();
filesToUpload.add(new File(Environment.getExternalStorageDirectory(), "file1.txt"));
filesToUpload.add(new File(Environment.getExternalStorageDirectory(), "file2.txt"));
int threadCount = 3;
MultiThreadBatchUploader uploader = new MultiThreadBatchUploader(uploadUrl, filesToUpload, threadCount);
uploader.startUpload();
}
}
请注意以下几点:
- 这只是一个示例,实际应用中你需要处理更多的错误情况,如网络连接问题、文件不存在等。
- 在 Android 应用中,确保你有适当的权限来访问外部存储和进行网络操作,并且应该在非主线程中执行网络操作以避免阻塞主线程。