本帖最后由 梁航斌 于 2013-4-10 20:02 编辑
PrintWriter用起来很方便,还能自动刷新,可是我自己写了个客户端上传图片到服务端的例子出问题了,图片大小变小了。我怀疑是pw.write(new String(buf,0,len));这里出的问题,我自己后来换了BufferedOutputStream就解决了,但是请问PrintWriter这个问题怎么解决呢,我加了flush()比不加的时候得出的图片要大几K,不是自动刷新吗?怎么差别就那么大呢?
上代码了- import java.io.*;
- import java.net.*;
- //客户端
- class Client
- {
- public static void main(String args[]) throws Exception{
- if(args.length!=1){
- System.out.println("一次仅能传送一张图片");
- return;
- }
- if(!args[0].endsWith(".jpg")){
- System.out.println("请注意图片格式,仅支持.jpg");
- return;
- }
- File file = new File(args[0]);
- if(file.length() > 1024*1024*5){
- System.out.println("文件不能超过5M");
- return;
- }
- System.out.println(args[0]);
- //建立Socket指向发送没标和端口
- Socket s = new Socket(InetAddress.getByName("192.168.1.4"),10000);
- //建立读取流对象,采用BufferedInputStream读取本地图片
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
- //获取Socket对象的写入流,封装成PrintWriter提高效率
- PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
- //定义字节缓冲区
- byte []buf = new byte[1024];
- int len = 0;
- //循环读取写入到服务端
- while((len = bis.read(buf))!=-1){
- pw.write(new String(buf,0,len));
- }
- //告诉服务端这边写完了
- s.shutdownOutput();
- //获取Socket读取流,封装BufferedInputStream读取服务端返回的数据
- BufferedInputStream rbis = new BufferedInputStream(s.getInputStream());
- //因为就一句话,所以就不用循环了
- byte []b = new byte[1024];
- int num = rbis.read(b);
- System.out.println(new String(b,0,num));
- rbis.close();
- pw.close();
- s.close();
- }
- }
复制代码- import java.io.*;
- import java.net.*;
- class Server
- {
- public static void main(String []args) throws Exception{
- //建立服务端对象,监听10000端口
- ServerSocket ss = new ServerSocket(10000);
- //循环控制客户端运行各自的线程
- while(true){
- //accept()是阻塞式的,因此不会陷入死循环
- Socket s = ss.accept();
- //开启对象各自的线程
- new Thread(new UpLoad(s)).start();
- }
- }
- }
- class UpLoad implements Runnable
- {
- private Socket s;
- UpLoad(Socket s){
- this.s = s;
- }
- public void run(){
- try{
- //当客户端连接成功后服务端显示其ip
- String ip = s.getLocalAddress().getHostAddress();
- System.out.println(ip+"......连接成功");
- //定义计数器
- int count = 1;
- //定义一个File,用ip为图片命名,避免同名采用循环判断
- File file = new File("D:\\"+ip+".jpg");
- if(file.exists()){
- file = new File("D:\\"+ip+"("+(count++)+")"+".jpg");
- }
- //获取Socket对象的读取流,采用BufferedInputStream提高效率
- BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
- //写入流采用PrintWriter
- PrintWriter pw = new PrintWriter(new FileOutputStream(file),true);
- byte []buf = new byte[1024];
- int len = 0;
- while((len = bis.read(buf))!=-1){
- pw.write(new String(buf,0,len));
- }
- //告诉客户端这边读完了
- s.shutdownInput();
- //获取Socket对象的写入流,然后发送“上传成功”给客户端
- PrintWriter rpw = new PrintWriter(s.getOutputStream());
- rpw.write("上传成功");
- rpw.flush();
- rpw.close();
- pw.close();
- s.close();
- }
- catch(Exception e){
-
- }
- }
- }
复制代码 |