我通过 TCP 将文件从一个 android 设备发送到另一个。当我尝试发送 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;
}