抱歉英文不好,我用谷歌翻译。
处理需要通过网络传输文件且能够恢复的应用程序,该程序可以正常工作,但是为什么当您打开通过nano传输的文本文件时,看到数据是重复的。
服务器
OutputStream outToClient = socket.getOutputStream();
File myfile = new File(filePath);
System.out.println("файл " + myfile.toString());
byte[] mybytearray = new byte[(int) myfile.length()];
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myfile));
BufferedOutputStream bost = new BufferedOutputStream(new FileOutputStream(new File(filePath+"111")));
bost.write(mybytearray, 0, mybytearray.length);
bis.skip(filePosition);
bis.read(mybytearray, 0, mybytearray.length);
bost.write(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
bis.close();
客户端
byte[] mybytearray = new byte[1024];
fos = new FileOutputStream(fullPath, true);
bos = new BufferedOutputStream(fos);
InputStream is = socket.getInputStream();
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
do {
baos.write(mybytearray);
bytesRead = is.read(mybytearray);
if (bytesRead != -1)
filePosition += bytesRead;
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.close(); socket.close();
is.close();
socket.close();
答案 0 :(得分:0)
您将获得一些重复数据,因为在使用新数据填充数组之前,您将相同的数组内容写入输出文件两次。你没有很好地使用这些流。尝试更像这样的东西:
服务器
OutputStream outToClient = socket.getOutputStream();
byte[] mybytearray = new byte[1024];
File myfile = new File(filePath);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(myfile));
bis.skip(filePosition);
do {
int bytesRead = bis.read(mybytearray, 0, mybytearray.length);
if (bytesRead <= 0) {
break;
}
outToClient.write(mybytearray, 0, bytesRead);
}
white (true);
outToClient.flush();
bis.close();
客户端
byte[] mybytearray = new byte[1024];
//todo: seek the output file to the starting filePosition
//instead of just appending to the end of the file...
fos = new FileOutputStream(fullPath, true);
bos = new BufferedOutputStream(fos);
InputStream is = socket.getInputStream();
do {
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
if (bytesRead <= 0) {
break;
}
bos.write(mybytearray, 0, bytesRead);
filePosition += bytesRead;
} while (true);
bos.close();
is.close();
socket.close();