黑马程序员技术交流社区

标题: 关于java网络编程上传图片问题 [打印本页]

作者: 杨剑    时间: 2013-3-5 12:04
标题: 关于java网络编程上传图片问题
import java.io.*;
import java.net.*;
class PicClient{
public static void main(String[] args) throws Exception{
  Socket s = new Socket("192.168.1.121",10001);
  FileInputStream fis = new FileInputStream("f:\\chat.png");
  byte[] buf = new byte[1024];
  int len = 0;
  OutputStream os = s.getOutputStream();
  while((len=fis.read(buf))!=-1){
   os.write(buf,0,len);
  }
  s.shutdownInput();
  InputStream is = s.getInputStream();
  byte[] bufIn = new byte[1024];
  int len2 = is.read(bufIn);
  System.out.println(new String(bufIn,0,len2));
  fis.close();
  os.close();
  is.close();
}
}
class PicServer{
public static void main(String[] args)throws Exception{
  ServerSocket ss = new ServerSocket(10001);
  Socket s = ss.accept();
  InputStream is = s.getInputStream();
  byte[] buf = new byte[1024];
  FileOutputStream fos = new FileOutputStream("2.jpg");
  int len = 0;
  while((len=is.read(buf))!=-1){
   fos.write(buf,0,len);
  }
  PrintWriter pw = new PrintWriter(s.getOutputStream());
  pw.println("上传成功".getBytes());
  is.close();
  fos.close();
  pw.close();
}
}
上传图片的时候遇到这个问题,不知道怎么回事

wenti.png (35.01 KB, 下载次数: 13)

wenti.png

作者: BitmapFactory    时间: 2013-3-5 14:05
在第13行应该关闭输出流,而非输入流s.shutdownOutput();
第34行PrintWriter pw = new PrintWriter(s.getOutputStream());打印流可以自动刷新,但要多输入一个参数
PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
打印流可以直接打印的 pw.println("上传成功".getBytes());
去掉.getBytes()

作者: 杨剑    时间: 2013-3-13 20:00
我知道了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2