使用java socket 实现大文件传输,在传输大文件时总会抛出一次异常:java.io.UTFDataFormatException: malformed input around byte 1
发送端
while ((i = fin.read(outBytes)) > 0) {
dataOutputStream.writeUTF("003");
long point = position * outBytes.length;
dataOutputStream.writeLong(point);// 当前指针位置,接收端从此处开始写入
dataOutputStream.writeInt(i); // 数据长度
dataOutputStream.write(outBytes, 0, i); // 发送端执行到这里抛出broke pipe
dataOutputStream.flush();
position = position + 1;
}
接收端
operate = in.readUTF(); // 接收端这里抛出异常
case "003": {
// 处理发送的文件(接收)
try (RandomAccessFile randomAccessFile = new RandomAccessFile(enPath, "rw")) {
// 游标位置
long pos = in.readLong();
// 数据长度
int inputSize = in.readInt();
byte[] eoutBytes = new byte[inputSize];
in.read(eoutBytes);
// 将游标跳到指定位置
randomAccessFile.seek(pos);
randomAccessFile.write(eoutBytes, 0, inputSize);
pre = pos - inputSize;
transferFile.setCur(pre);
}
return true;
}
发送端循环发送003,游标位置,数据长度,数据内容
接收端循环读取utf,long,int,byte[]
因为在传输小文件时不会抛出java.io.UTFDataFormatException: malformed input around byte 1
,传输大文件时总会在等待一个特定的时间抛出异常,所以怀疑是不是有某个队列满了导致operate=in.readUTF()
读取到错误的数据.但找不到问题所在