java中的socket传文件的问题
weixn 2004-12-10 01:29:25 写了段代码用socket传送文件,可是为什么收到的文件比传送过去的内容要少?
收到的文件都打不开。高手请帮我看看?
万分感谢!
//传文件
private String putFile(String ip,String filename){
Socket tempSocket = null ; //临时socket,用于传送文件
String returnmsg="";
System.out.println(" put file --- 150 Binary data connection");
try{
//创建用于传送文件的临时socket
filename=filename+".zip";
tempSocket = new Socket(ip,server_port);
//找文件
RandomAccessFile outFile = new RandomAccessFile(report_dir+filename,"r");
//读文件
OutputStream outSocket = tempSocket.getOutputStream();
PrintWriter tempout=new PrintWriter(outSocket,true);
//文件传送标志
tempout.println("---put file---");
tempout.println(filename);
//开始传送文件
byte byteBuffer[]= new byte[1024];
int amount;
while((amount = outFile.read(byteBuffer)) != -1){
outSocket.write(byteBuffer,0, amount); }
outFile.close();
//关闭
outSocket.close();
}catch(FileNotFoundException e2){
returnmsg="send file errorm,file not exit:"+report_dir+filename+"!"+e2;
}catch(IOException e4){
returnmsg="send file error!/n"+e4;
}finally{
//关闭socket
try{
tempSocket.close() ;
}catch(IOException e3){}
}
return returnmsg;
}
//建立连接后,取收到的数据
line=in.readLine();
if(line.equals("---put file---")){
line=in.readLine();
getFile(line);
}
//接收文件
private void getFile(String filename){
try{
//新建文件
File file_report=new File(file_dir+setFileName(filename));
if(!file_report.exists()) file_report.createNewFile();
RandomAccessFile inFile = new RandomAccessFile(file_report,"rw");
byte byteBuffer[] = new byte[1024];
int amount;
//接收并写入新文件
while((amount =inSocket.read(byteBuffer))!= -1){
inFile.write(byteBuffer, 0, amount);
}
inSocket.close();
inFile.close();
}catch(FileNotFoundException e2){
System.out.println(e2);
}catch(IOException e4){
System.out.println(e4);
}
}