我知道为什么我的问题正在发生,但我不知道如何解决它。我通过发送以下内容将多个文件从发件人发送到接收者:
我正在使用readInt()
,readUTF()
和readLong()
发送我列表中的前3个。
对于文件数据,我通过实现以下代码来使用缓冲区:
float bytesRead = 0;
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
bytesRead += count;
Float[] progressData = {(bytesRead / 1000), (float) (size / 1000), (float) i, (float) totalFileCount};
publishProgress(progressData);
}
我正在使用for循环来发送文件的所有细节。
这里的问题是,在读取第一个文件的数据后,接收器将下一个文件的名称也作为第一个文件的数据读取。我需要以某种方式让它在达到第一个文件的大小后停止阅读。但我无法实现这一点。任何帮助表示赞赏。
这是接收和发送数据的代码:
发送
try {
Socket client = new Socket();
client.bind(null);
client.connect(new InetSocketAddress(groupOwnerAddress, 8888));
if(client.isConnected())
{
((FileTransferActivity) context).setStatus("Connected to Device");
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeInt(encryptedFiles.size()); // send number of files
for(int i = 0; i < encryptedFiles.size(); i++)
{
long length = encryptedFiles.get(i).length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
} else {
out.writeUTF(encryptedFiles.get(i).getName()); //send file name
out.writeLong(length); // send file length
DataInputStream in = new DataInputStream(new FileInputStream(encryptedFiles.get(i)));
float bytesRead = 0;
int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
bytesRead += count;
Float[] progressData = {(bytesRead / 1000), (float) (length / 1000), (float) i, (float) encryptedFiles.size()};
publishProgress(progressData);
}
}
}
}
client.close();
} catch (IOException e) {
e.printStackTrace();
}
接收
File directory = new File(directoryPath);
if(!directory.exists())
directory.mkdirs();
String data = null;
try {
server = new ServerSocket(8888);
client = server.accept();
DataInputStream in = new DataInputStream(client.getInputStream());
int totalFileCount = in.readInt();
for(int i = 0; i < totalFileCount; i++)
{
String fileName = in.readUTF();
long size = in.readLong();
FileOutputStream out = new FileOutputStream(new File(directoryPath + File.separator + fileName));
float bytesRead = 0;
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
bytesRead += count;
Float[] progressData = {(bytesRead / 1000), (float) (size / 1000), (float) i, (float) totalFileCount};
publishProgress(progressData);
}
}
}
catch (IOException e) {
e.printStackTrace();
}
我在这里省略了asynctask的其他功能,因为我认为它们不相关。在任何情况下,如果你想让我也包含它,只需在评论中提及它,我会用它们更新我的答案
答案 0 :(得分:1)
我没有通过javac运行它,但它应该可以工作:
int count;
byte[] buffer = new byte[8192];
while (size > 0 && (count = in.read(buffer, 0, Math.min((int) size, buffer.length))) > 0) {
size -= count;
out.write(buffer, 0, count);
// Progress reporting omitted.
}