2016-08-03 5 views
1

현재 한 위치에서 다른 위치로 파일을 전송할 수있는 파일 전송 프로그램을 만들려고합니다. 이 프로그램은 .txt 파일에서 작동하지만 .exe와 같은 다른 확장 프로그램의 경우 전송 된 파일이 제대로 열리지 않습니다. 코드에 문제가있는 사람이 있습니까? 감사!Java 소켓을 통한 파일 송수신

서버 코드 :

import java.io.*; 
import java.net.*; 

public class SendFile{ 
    static ServerSocket receiver = null; 
    static OutputStream out = null; 
    static Socket socket = null; 
    static File myFile = new File("C:\\Users\\hieptq\\Desktop\\AtomSetup.exe"); 
    /*static int count;*/ 
    static byte[] buffer = new byte[(int) myFile.length()]; 
    public static void main(String[] args) throws IOException{ 
     receiver = new ServerSocket(9099); 
     socket = receiver.accept(); 
     System.out.println("Accepted connection from : " + socket); 
     FileInputStream fis = new FileInputStream(myFile); 
     BufferedInputStream in = new BufferedInputStream(fis); 
     in.read(buffer,0,buffer.length); 
     out = socket.getOutputStream(); 
     System.out.println("Sending files"); 
     out.write(buffer,0, buffer.length); 
     out.flush(); 
     /*while ((count = in.read(buffer)) > 0){ 
      out.write(buffer,0,count); 
      out.flush(); 
     }*/ 
     out.close(); 
     in.close(); 
     socket.close(); 
     System.out.println("Finished sending"); 



    } 

} 

클라이언트 코드 :의 InputStream 번호가 상태를 읽어

byteread = is.read(buffer, 0, buffer.length); 
    current = byteread; 

    do{ 
     byteread = is.read(buffer, 0, buffer.length - current); 
     if (byteread >= 0) current += byteread; 
    } while (byteread > -1); 

의 InputStream

에서 읽는 동안

import java.io.*; 
import java.net.*; 

public class ReceiveFile{ 
    static Socket socket = null; 
    static int maxsize = 999999999; 
    static int byteread; 
    static int current = 0; 
    public static void main(String[] args) throws FileNotFoundException, IOException{ 
     byte[] buffer = new byte[maxsize]; 
     Socket socket = new Socket("localhost", 9099); 
     InputStream is = socket.getInputStream(); 
     File test = new File("D:\\AtomSetup.exe"); 
     test.createNewFile(); 
     FileOutputStream fos = new FileOutputStream(test); 
     BufferedOutputStream out = new BufferedOutputStream(fos); 
     byteread = is.read(buffer, 0, buffer.length); 
     current = byteread; 

     do{ 
      byteread = is.read(buffer, 0, buffer.length - current); 
      if (byteread >= 0) current += byteread; 
     } while (byteread > -1); 
     out.write(buffer, 0, current); 
     out.flush(); 

     socket.close(); 
     fos.close(); 
     is.close(); 

    } 
} 

답변

1

하나의 문제는 당신이 당신의 buffer의 내용을 덮어 쓰는 것입니다 두 번째 param은 바이트 배열로 저장되며 오프셋이 적용됩니다. offset은 항상 0이므로 각 반복에서 덮어 씁니다.

내가 InputStream로부터 읽고이 도움이

byte[] buffer = new byte[16384]; 

while ((byteread = is.read(buffer, 0, buffer.length)) != -1) { 
    out.write(buffer, 0, byteread); 
} 

out.flush(); 

희망을 OutputStream에 작성의 논리를 단순화하기 위해 제안

.

+0

와우, 이제 작동합니다. –

+0

도움이 된 것을 기쁘게 생각합니다 :) – Sanjeev