0

ある Android デバイスから別の Android デバイスに TCP 経由でファイルを送信しています。mp3ファイルを送ろうとしたとき。無事受け取りました。しかし、ファイルが壊れました。(ターゲットデバイスにまったく同じサイズのファイルがあります)。
私の受け手は

input = new DataInputStream( clientSocket.getInputStream());
output =new DataOutputStream( clientSocket.getOutputStream()); 

int fileLength = input.readInt();
System.out.println("test integer recived"+fileLength);
String actualFileName = "";
    for(int i=0;i<fileLength;i++){
    actualFileName =actualFileName+input.readChar(); 
    }
Log.d(loggerTag,"file is going to be recieved"+actualFileName  );

File file =new File("/*my file location*/"+actualFileName); 
Log.d(loggerTag,"file is going to be saved at"+file.getAbsolutePath()  );
long temp = input.readLong();
byte[] rFile = new byte[ (int) temp ];
input.read( rFile );
FileProcess.makeFile(, rFile);          
FileOutputStream outStream = new FileOutputStream(file.getAbsolutePath());
outStream.write( rFile);
Log.d(loggerTag, "file success fully recived");
outStream.close();

送信者は

s = new Socket(IP, serverPort);
DataInputStream input = new DataInputStream( s.getInputStream());
DataOutputStream output = new DataOutputStream( s.getOutputStream()); 

String actualFileName = StringUtil.getFileName(fileName);
output.writeInt(actualFileName.length());
Log.d(loggerTag, "sending file name");
   for(int i =0;i<actualFileName.length();i++){
   output.writeChar(actualFileName.charAt(i));
   }

File file = new File(fileName);
Log.d(loggerTag, "file going to send"+fileName);

output.writeLong(file.length() );
output.write( FileProcess.getBytes( file ) );
Log.d(loggerTag, "file sending finshed");

public static byte[] getBytes( File path ) throws IOException {
    InputStream inStream = new FileInputStream( path );
    long length = path.length();
    byte[] file = new byte[ (int) length ];

    int offset = 0, numRead = 0;        
    while ( offset < file.length && ( numRead = inStream.read( file, offset, file.length - offset ) ) > -1 ) {
        offset += numRead;
    }

    if (offset < file.length) {
        throw new IOException( "Error: A problem occurs while fetching the file!" );
    }

    inStream.close();
    return file;
}
4

1 に答える 1