わかりました.... Javaを独学で学ぼうとしているのですが、しばらくこれに悩まされていました。ソケットとバッファリングされた入出力ストリームを使用して、ネットワーク経由で大きなファイルを転送しようとしています。転送しようとするファイルのサイズは関係ありません。コードを正しく投稿したことを願っています。このコードにはおそらく多くの問題があることを知っていますが、コンパイルして正常に実行されますが、クライアントとサーバーが while ループに入ると 2 番目に 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");
}
}