2011-04-29 42 views
0

嗨,这是我的客户端程序传输图像,同时传输图像文件它已经损坏,无法打开该图像文件,我无法识别错误,任何一个帮我。无法传输图像文件

DataInputStream input = new DataInputStream(s.getInputStream()); 

DataOutputStream output = new DataOutputStream(s.getOutputStream()); 

System.out.println("Writing......."); 

FileInputStream fstream = new FileInputStream("Blue hills.jpg"); 

DataInputStream in = new DataInputStream(fstream); 

byte[] buffer = new byte[1000]; 
int bytes = 0; 

while ((bytes = fstream.read(buffer)) != -1) { 
    output.write(buffer, 0, bytes); 
} 

in.close(); 

回答

0

我认为sSocket,你正在试图文件通过网络传输?这是一个用套接字发送文件的例子。它只是在一个线程中建立一个服务器套接字并连接到它自己。

public static void main(String[] args) throws IOException { 
    new Thread() { 
     public void run() { 
      try { 
       ServerSocket ss = new ServerSocket(3434); 
       Socket socket = ss.accept(); 
       InputStream in = socket.getInputStream(); 
       FileOutputStream out = new FileOutputStream("out.jpg"); 
       copy(in, out); 
       out.close(); 
       in.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    }.start(); 

    Socket socket = new Socket("localhost", 3434); 
    OutputStream out = socket.getOutputStream(); 
    FileInputStream in = new FileInputStream("in.jpg"); 
    copy(in, out); 
    out.close(); 
    in.close(); 
} 

public static void copy(InputStream in, OutputStream out) throws IOException { 
    byte[] buf = new byte[8192]; 
    int len = 0; 
    while ((len = in.read(buf)) != -1) { 
     out.write(buf, 0, len); 
    } 
} 
+0

我试过这个方法它被执行但文件没有被复制 – 2011-05-03 08:48:59

+0

本地或计算机之间?我证实它适用于本地。 – WhiteFang34 2011-05-03 09:00:30

+0

好的,我会仔细检查,谢谢你的帮助我 – 2011-05-03 09:04:25