我认为应该是: while((len=bisFile.read())!=-1); 这句话中bisFile.read()有可能出问题,你看了毕老师的复制mp3的视频讲解就知道,由于图片在内存中使用的是二进制数据存储的,这里的read方法就有可能读取到某一部分就读取到了连续的11111111时转换成int型的就编程-1,此时就跳出了while循环,所以读取不到整个文件。同理,在server类中 while((len=bis.read())!=-1)也可能出现这种情况。你用数组读取就应该没有这种问题了。
- import java.net.*;
- import java.io.*;
- class PicClient
- {
- public static void main(String[] args) throws Exception
- {
- Socket s = new Socket("192.168.1.120",10086);
- BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\1.jpg"));
- BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
- BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
-
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=bis.read(buf))!=-1)
- {
- bos.write(buf,0,len);
- bos.flush();
- }
- s.shutdownOutput();
- String line = br.readLine();
- System.out.println(line);
- bis.close();
- bos.close();
- br.close();
- s.close();
- }
- }
复制代码- package com.itheima.test;
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.BufferedWriter;
- import java.io.FileOutputStream;
- import java.io.OutputStreamWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class PicServer {
- public static void main(String[] args) throws Exception {
- ServerSocket ss = new ServerSocket(10086);
- Socket s = ss.accept();
-
- BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
- BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("D://2.jpg"));
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
-
- byte[] buf = new byte[1024];
- int len = 0;
- while((len=bis.read(buf))!=-1){
- bos.write(buf,0,len);
- bos.flush();
- }
-
- bw.write("上传成功!!!");
- bw.flush();
-
- bis.close();
- bos.close();
- bw.close();
- s.close();
- ss.close();
- }
- }
复制代码
|