本帖最后由 李志卫 于 2013-2-24 21:39 编辑
以下例子要求上传图片
但我写的例子图片上传后有所损坏,为什么呢?
import java.net.*;
import java.io.*;
class TcpClient
{
public static void main(String[] args) throws Exception
{
Socket s = new Socket("192.168.1.2",10005);
File file = new File("C:\\星空.jpg");
BufferedInputStream bfi = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bfo = new BufferedOutputStream (s.getOutputStream());
BufferedReader bfr = new BufferedReader(new InputStreamReader(s.getInputStream()));
int by = 0;
while((by=bfi.read())!=-1)
{
bfo.write(by);
}
s.shutdownOutput();
String line = null;
while((line=bfr.readLine())!=null)
System.out.println(line);
s.close();
bfi.close();
bfo.close();
bfr.close();
}
}
class TcpServer
{
public static void main(String[] args) throws Exception
{
ServerSocket ss = new ServerSocket(10005);
Socket s = ss.accept();
File file = new File("F:\\星空.jpg");
String ip = s.getInetAddress().getHostAddress();
BufferedInputStream bfi = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bfo = new BufferedOutputStream (new FileOutputStream(file));
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
System.out.println(ip+"...正在上传。");
int by = 0;
while((by=bfi.read())!=-1)
{
bfo.write(by);
}
pw.println("文件上传成功");
s.shutdownOutput();
s.close();
ss.close();
bfi.close();
bfo.close();
pw.close();
}
}
|