好的....尝试自己学习java,有一段时间遇到了麻烦。我正在尝试使用套接字和缓冲的输入和输出流通过网络传输一个大文件。不管我尝试传输什么大小的文件。希望我正确发布了我的代码,我知道这段代码可能存在很多问题,尽管它编译并运行正常,但在客户端和服务器进入 while 循环的第二次我得到一个 IndexOutOfBoundsException,服务器在第一次 bis.read 期间得到它(buf,0,len) 并且客户端在 while(off = fis.read(buf,0,len) ..... 任何帮助将不胜感激
//Server Receive code receive method and main for testing
public File receive(Socket socket) throws IOException{
//temporarily hard coded filename
File file = new File("C:\\users\\tom5\\desktop\\sales\\input.dat");
DataInputStream dis = new DataInputStream(socket.getInputStream());
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
//reads file length from datainputstream
int len = dis.readInt();
dis.close();
int bytesRead=0;
//create buffer
byte[]buf = new byte[4092];
int off = 0;
//read from BufferedInputStream and write to FileOutputStream?
while(bytesRead < len) {
bis.read(buf,0,len);
fos.write(buf,0,len);
bytesRead++;
}
fos.close();
bis.close();
return file;
}
public static void main(String[]args) throws IOException{
Server server = new Server();
Socket socket =server.accept();
File file = server.receive(socket);
}
}
//Client sending code
public void send(Socket socket,File file) throws IOException{
FileInputStream fis = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
int len = (int)file.length();
dos.writeInt(len);
dos.flush();
dos.close();
System.out.println(file.length());
byte[]buf = new byte[4092];
int off= 0;
while((off = fis.read(buf,0,len)) != -1 ){
bos.write(buf,0,len);
}
}
public static void main(String[]args) throws UnknownHostException, IOException{
Client client = new Client();
Socket socket =client.connect("localhost",1055);
File file = new File("C:\\users\\tom5\\desktop\\movie.avi");
}
}