救命啊!java Tcp上传文件竟然丢失部分数据!!!

山外客 2014-08-31 06:26:01
如题!我上传的是个MP3文件,丢了16K数据


//客户端
import java.io.*;
import java.net.*;
/*
* 需求:客户端并发上传图片
*/
public class Tcp练习4
{
public static void main(String [] args)throws Exception
{
if(args.length!=1)
{
System.out.println("输入信息长度必须唯一");
return;
}
String filename=args[0];

File file=new File(filename);

if(!(file.exists()&&file.isFile()))
{
System.out.println("文件不存在或不是文件");
return;
}

Socket soc=new Socket(InetAddress.getLocalHost(),9000);



FileInputStream fr=new FileInputStream(file);

OutputStream out=soc.getOutputStream();
InputStream in=soc.getInputStream();

System.out.println(filename);

//将文件名发给客户端
PrintStream pp=new PrintStream(out,true);
pp.println(filename);


int len;
byte [] buf=new byte[1024];
while((len=fr.read(buf))!=-1)
{
out.write(buf,0,len);
}
soc.shutdownOutput();

len=in.read(buf);
System.out.println(new String(buf,0,len));

soc.close();
in.close();
out.close();
fr.close();

}
}

//服务端
//package a;
import java.io.*;
import java.net.*;
/*
* 客户端的并发上传文件的原理。(凡是服务器都这样)
* 获得一个连接启动一个线程(run方法)
*/
class FileThread implements Runnable
{
private Socket soc;
FileThread(Socket soc)
{
this.soc=soc;
}
public void run()
{


try
{
String ip=soc.getInetAddress().getHostAddress();

System.out.println(ip+" connected");

InputStream in=soc.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String path=br.readLine();
//System.out.println(name);
//String [] ss=name.split("/.");
String name=path.substring(0, path.lastIndexOf('.'));
String format=path.substring(path.lastIndexOf('.'));



int count=1;
byte [] buf=new byte[1024];
int len;
//stem.out.println(ss.length);
File file=new File(name+"("+count+")"+format);
while(file.exists())
{
count++;
file=new File(name+"("+count+")"+format);
}


FileOutputStream fos=new FileOutputStream(file);//////////////////////////////////
OutputStream out=soc.getOutputStream();




while((len=in.read(buf))!=-1)
{
fos.write(buf, 0, len);

}

out.write("上传成功".getBytes());
in.close();
out.close();
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
throw new RuntimeException("服务端出错");
}
}
}
public class 练习Server4
{
public static void main(String [] ars)throws Exception
{
ServerSocket sersoc=new ServerSocket(9000);
while(true)
{
Socket soc=sersoc.accept();
new Thread(new FileThread(soc)).start();
}

}
}
...全文
186 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧