2014-10-14 1 views
0

연결하는 클라이언트 서버를 실행할 때 파일을 보내려고하면 오류를 가져 오는 전체 파일을 보내지 않습니다. 끊임없이 같은 부분에서 멈 춥니 다. 동일한 시스템에 서버 - 클라이언트를 실행하는 경우클라이언트 - 서버가 전체 파일을 보내지 않음

  // input (a DataInputstream) is set up elsewhere and messages are sent and received properly 
      String FILE_TO_RECEIVED = "Load_From.xml"; 
      File file = new File(FILE_TO_RECEIVED); 

      int FILE_SIZE = input.readInt(); 
      if(FILE_SIZE!=0){ 
       // receive file 
       System.out.println("received file size : " + FILE_SIZE); 
       byte [] mybytearray = new byte [FILE_SIZE]; 
       FileOutputStream fos = new FileOutputStream(file); 
       BufferedOutputStream bos = new BufferedOutputStream(fos); 
       int bytesRead = input.read(mybytearray, 0, mybytearray.length); 
       bos.write(mybytearray, 0, bytesRead); 
+0

어디서 멈 춥니 까? 작은 파일 (예 : 2KB)에서도 작동합니까? –

답변

2

에만있는 내가

서버 --->

// output (a DataOutputstream) is set up elsewhere and messages are sent and received properly 
    output.writeInt((int)file.length()); 
    // send file 

    byte [] mybytearray = new byte [(int)file.length()]; 
    FileInputStream fis = new FileInputStream(file); 
    BufferedInputStream bis = new BufferedInputStream(fis); 
    bis.read(mybytearray,0,mybytearray.length); 
    System.out.println("Sending " + file + "(" + mybytearray.length + " bytes)"); 
    output.write(mybytearray,0,mybytearray.length); 
    output.flush(); 
    System.out.println("Done."); 

클라이언트 ---> 완전히 혼란 스러워요 그래서이 작품을 설정 파일을 읽을 때와 소켓을 읽을 때 데이터의 일부분을 읽습니다. read 메서드는 읽은 바이트 수를 반환하며 모든 것을 읽으려면 루프가 필요합니다. 예를 들어,

int read = 0, offset = 0; 
while ((read = bis.read(mybytearray, offset, mybytearray.length - offset) != -1) { 
    offset += read; 
} 

아니면 예를 DataInputStream를 들어, 표준 라이브러리에서 클래스를 사용할 수는 readFully 방법이있다.

DataInputStream dis = new DataInputStream(fis); 
dis.readFully(mybytearray); 
+0

dis.readFully (mybytearray)를 사용하여 파일로 변환하는 방법은 무엇입니까? –

+0

바이트 만 파일에 기록하면됩니다. 이미 가지고있는 코드는 괜찮아 보입니다. – Joni

2

에서 read()의 문서를 참조하십시오 http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[],%20int,%20int)합니다. 특히

은 :

시도가 len 바이트만큼을 읽으려고하지만, 작은 수를 읽을 수 있습니다. 실제로 읽힌 바이트 수는 정수로 반환됩니다.

즉, 반환 된 길이가 예상 한 것과 같지 않고 아직 파일 끝을 발견하지 못했다면 read()를 다시 호출해야합니다.

관련 문제