2017-11-13 2 views
2

파일 목록에서 Zip 파일을 만드는 함수가 있습니다. 디스크에 저장하지 않고 Zip 파일을 반환 할 수 있습니까? 다른 함수의 매개 변수로 zip 파일을 사용해야하므로 파일이 필요합니다. 나는 ByteStream이 나를위한 옵션이 될지 확신하지 못한다.자바에서 ZipOutputStream에서 Zip 파일을 반환하십시오.

public File compressFileList(List<File> fileList,String fileName) { 
    FileOutputStream fileOutputStream=null; 
    ZipOutputStream zipOutputStream=null; 
    FileInputStream fileInputStream=null; 
    String compressedFileName=fileName +".zip"; 
    if(fileList.isEmpty()) 
     return null; 
    try 
    { 
     fileOutputStream = new FileOutputStream(compressedFileName); 
     zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream)); 
     for (File file: fileList) { 
      fileInputStream = new FileInputStream(file); 
      ZipEntry zipEntry = new ZipEntry(file.getName()); 
      zipOutputStream.putNextEntry(zipEntry); 
      byte[] tmp = new byte[4*1024]; 
      int size = 0; 
      while((size = fileInputStream.read(tmp)) != -1){ 
       zipOutputStream.write(tmp, 0, size); 
      } 
      zipOutputStream.flush(); 
      fileInputStream.close(); 
     } 
     zipOutputStream.close(); 
     return compressedFile; //This is what I am missing 

    } 
    catch (FileNotFoundException e) 
    { 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

편집 :

아이디어는 zip 파일을 생성하고 왓슨의 VisualRecognition 서비스의 CreateClassifierOptions 방법을 사용하는 것입니다 유스 케이스를 추가.

classifierOptions = new CreateClassifierOptions.Builder() 
      .classifierName("Santa") 
      .addClass("Santa", new File("C:\\app\\GitRepo\\images\\beagle.zip")) 
      .negativeExamples(new File("C:\\app\\GitRepo\\images\\nosport.zip")) 
      .build(); 

빌더는 zip 파일을 매개 변수로 허용합니다. 알렉상드르 Dupriez의 설명을 바탕으로

이해

, 나는 하드 디스크에 어떤 장소에 파일을 저장하는 것이 좋습니다 생각합니다.

+1

다른 함수는 입력으로 무엇을 동의 하는가? 'Inputstream'? – Lino

+0

Zip 파일을 입력으로 허용하는 WatsonService API를 사용하고 있습니다.또는 어쩌면 내가 임시 zip 파일을 만들고 함수에 반환해야합니다. – Vini

+0

질문이 메서드 서명과 충돌합니다. File 객체는 기본적으로 어떤 경로에 저장된 파일에 대한 참조이지만 파일의 (바이트) 내용을 반환하는 것과 관련하여 질문하는 것 같습니다. 따라서 파일을 어딘가에 저장하지 않으려면 File 객체를 반환하면 안됩니다. –

답변

3

당신은 ByteArrayOutputStream 대신 FileOutputStream의를 사용할 수 있어야합니다 :

zipOutputStream = new ZipOutputStream(new ByteArrayOutputStream()); 

여기 어려움은 zip 파일을 소비하는 방법에 File을 제공하는 것입니다. java.io.File은 메모리 내 파일을 조작 할 수있는 추상화를 제공하지 않습니다.

java.io.File 추상화와 java.io.FileInputStream 구현

우리는 File 추상화가 무엇인지로 요약해야한다면 단순화하기 위해, 우리는 그것이 URI으로 볼 것입니다. 따라서 메모리 내에서 File을 구축하거나 최소한 모방하려면 URI을 제공해야합니다. 그러면 File 소비자가 콘텐츠를 읽을 수 있습니다.

// class java.io.FileInputStream 
/** 
* Opens the specified file for reading. 
* @param name the name of the file 
*/ 
private native void open0(String name) throws FileNotFoundException; 
: 우리는 소비자가 사용할 가능성이있는 FileInputStream 보면

, 우리는 항상 메모리 파일을 추상화 FileSystem에 어떠한 가능성을 우리에게 제공하는 네이티브 호출로 끝나는 것을 볼 수 있습니다

InputStream을 수락하도록 소비자를 적응시킬 가능성이있는 경우 더 쉬울 것이지만 문제 성명서에서 나는 이것이 가능하지 않다고 생각합니다.

API 호출

귀하의 요구 사항은 왓슨 비주얼 API에 File을 제공하는 것입니다. 전화해야하는 API 메소드를 제공해 주시겠습니까?

+0

위의 함수가 File을 반환하도록합니다. 호출 함수는 Zip 파일 만 입력으로 허용합니다. – Vini

+0

예 - 내 게시물 편집 –

+0

이 SDK를 사용하고 있습니까? https://github.com/watson-developer-cloud/java-sdk? –

1
public void compressFileList(List<File> fileList, OutputStream outputStream) 
     throws IOException { 
    try (ZipOutputStream zipOutputStream = 
      new ZipOutputStream(new BufferedOutputStream(outputStream)); 
     for (File file: fileList) { 
      try (FileInputStream fileInputStream = new FileInputStream(file)) { 
       ZipEntry zipEntry = new ZipEntry(file.getName()); 
       zipOutputStream.putNextEntry(zipEntry); 
       byte[] tmp = new byte[4*1024]; 
       int size = 0; 
       while((size = fileInputStream.read(tmp)) != -1){ 
        zipOutputStream.write(tmp, 0, size); 
       } 
       zipOutputStream.flush(); 
      } catch (FileNotFoundException e) { // Maybe skip not found files. 
       Logger.log(Level.INFO, "File not found {}", file.getPath()); 
      } 
     } 
    } 
} 

사용법 :

if (fileList.isEmpty()) { 
    ... 
    return; 
} 
try { 
    compressFileList(fileList, servletRequest.getOutputStream())) { 
} catch (FileNotFoundException e) { 
    ... 
} catch (IOException e) { 
    ... 
} 
+0

파일을 반환하지 않습니다. zip 파일을 반환하는 옵션을 찾고 있습니다. 나는 다음 기능을 위해 파일을 사용하기 전에 임시로 파일을 저장해야한다는 것을 재확인했다. – Vini

+0

또는 (내 대답은 int로) zip 파일을 전달하기 위해 OutputStream을 전달할 수 있습니다. 그런 다음 zip 파일 내용으로 바이트 배열을 유지할 필요가 없습니다. –

관련 문제