2011-02-22 11 views
2

다른 파일 형식의 파일을 서버에서 클라이언트로 보내는 방법을 찾으려고합니다.서버에서 클라이언트로 Java 파일 보내기

나는 바이트 배열에 파일을 넣어 서버에서이 코드를 가지고 :

File file = new File(resourceLocation); 

byte[] b = new byte[(int) file.length()]; 
FileInputStream fileInputStream; 
try { 
    fileInputStream = new FileInputStream(file); 
    try { 
    fileInputStream.read(b); 
    } catch (IOException ex) { 
    System.out.println("Error, Can't read from file"); 
    } 
    for (int i = 0; i < b.length; i++) { 
    fileData += (char)b[i]; 
    } 
} 
catch (FileNotFoundException e) { 
    System.out.println("Error, File Not Found."); 
} 

내가 다음 클라이언트에 문자열로 FILEDATA을 보낼 수 있습니다. 이것은 txt 파일에 대해서는 문제없이 작동하지만 이미지에 관해서는 데이터가있는 파일을 잘 만들지 만 이미지는 열리지 않습니다.

내가 올바른 방향으로 가고 있는지 잘 모르겠습니다. 도움 주셔서 감사합니다.

+0

지금까지 답변 해 주셔서 감사합니다. – Undefined

답변

1

바이너리 데이터를 읽고 쓰는 경우 문자 스트림 대신 바이트 스트림 (InputStream/OutputStream)을 사용해야하며 예제에서와 같이 바이트와 문자 사이의 변환을 피하십시오.

당신은 OutputStream에로 InputStream로부터 바이트를 복사하려면 다음 클래스를 사용할 수 있습니다 :

public class IoUtil { 

    private static final int bufferSize = 8192; 

    public static void copy(InputStream in, OutputStream out) throws IOException { 
     byte[] buffer = new byte[bufferSize]; 
     int read; 

     while ((read = in.read(buffer, 0, bufferSize)) != -1) { 
      out.write(buffer, 0, read); 
     } 
    } 
} 

당신은 당신이 클라이언트와 연결하는 방법의 너무 많은 세부 사항을 제공하지 않습니다. 이것은 서블릿의 클라이언트에 몇 바이트를 스트리밍하는 방법을 보여주는 최소한의 예입니다. 응답에서 일부 헤더를 설정하고 자원을 적절하게 릴리스해야합니다.

public class FileServlet extends HttpServlet { 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     // Some code before 

     FileInputStream in = new FileInputStream(resourceLocation); 
     ServletOutputStream out = response.getOutputStream(); 

     IoUtil.copy(in, out); 

     // Some code after 
    } 
} 
2

char 문자가있는 문자열에는 넣지 마십시오. 그냥 소켓을 파일 입력 스트림에서 가져온 바이트 배열을 쓰게하십시오.

관련 문제