使用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;
}
**接收端**
```java
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()`讀取到錯誤的資料.但找不到問題所在
uj5u.com熱心網友回復:
也可能丟包了,資料不完整。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/163701.html
標籤:Java SE
