java - Duplication of data when receiving a file through a socket -
sorry bad english, used google translate.
working on application needs transfer file on network ability resume, program works, why when open text file transmitted through nano seen data duplicated.
server
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();
client
byte[] mybytearray = new byte[1024]; fos = new fileoutputstream(fullpath, true); bos = new bufferedoutputstream(fos); inputstream = socket.getinputstream(); int bytesread = is.read(mybytearray, 0, mybytearray.length); bos.write(mybytearray, 0, bytesread); bytearrayoutputstream baos = new bytearrayoutputstream(); { 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();
you getting duplicate data because writing same array contents output file twice before filling array new data. not using streams well. try more instead:
server
outputstream outtoclient = socket.getoutputstream(); byte[] mybytearray = new byte[1024]; file myfile = new file(filepath); bufferedinputstream bis = new bufferedinputstream(new fileinputstream(myfile)); bis.skip(fileposition); { int bytesread = bis.read(mybytearray, 0, mybytearray.length); if (bytesread <= 0) { break; } outtoclient.write(mybytearray, 0, bytesread); } white (true); outtoclient.flush(); bis.close();
client
byte[] mybytearray = new byte[1024]; //todo: seek output file starting fileposition //instead of appending end of file... fos = new fileoutputstream(fullpath, true); bos = new bufferedoutputstream(fos); inputstream = socket.getinputstream(); { 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();
Comments
Post a Comment