2014-03-26 33 views
8

我將從第三方庫獲取輸入流到我的應用程序。 我必須將這個輸入流寫入一個文件。將InputStream寫入Java中的文件的有效方法6

以下是代碼片段我想:

private void writeDataToFile(Stub stub) { 
    OutputStream os = null; 
    InputStream inputStream = null; 

    try { 

     inputStream = stub.getStream(); 
     os = new FileOutputStream("test.txt"); 
     int read = 0; 
     byte[] bytes = new byte[1024]; 

     while ((read = inputStream.read(bytes)) != -1) { 
      os.write(bytes, 0, read); 
     } 

    } catch (Exception e) { 

     log("Error while fetching data", e); 

    } finally { 
     if(inputStream != null) { 
      try { 
       inputStream.close(); 
      } catch (IOException e) { 
       log("Error while closing input stream", e); 
      } 
     } 
     if(os != null) { 
      try { 
       os.close(); 
      } catch (IOException e) { 
       log("Error while closing output stream", e); 
      } 
     } 
    } 
} 

有沒有更好的方法來做到這一點?

回答

25

既然你堅持使用Java 6,請你幫個忙,並使用番石榴和其Closer

final Closer closer = Closer.create(); 
final InputStream in; 
final OutputStream out; 
final byte[] buf = new byte[32768]; // 32k 
int bytesRead; 

try { 
    in = closer.register(createInputStreamHere()); 
    out = closer.register(new FileOutputStream(...)); 
    while ((bytesRead = in.read(buf)) != -1) 
     out.write(buf, 0, bytesRead); 
    out.flush(); 
} finally { 
    closer.close(); 
} 

假如你使用的Java 7,該解決方案將是簡單:

final Path destination = Paths.get("pathToYourFile"); 
try (
    final InputStream in = createInputStreamHere(); 
) { 
    Files.copy(in, destination); 
} 

yourInputStream本應已自動關閉,作爲「獎勵」; Files本身會處理destination

+0

文件和路徑是Java 7中的概念,但是我的應用程序正在運行Java 6. 在Java 6中是否有像上述這樣的解決方案。 – Awesome

+0

Aw shucks。好的,那麼你可以使用外部庫嗎? InputStream出來了,我在想這裏的番石榴 – fge

+0

? – Puce

1

它可以得到與OutputStreamWriter清潔:

OutputStream outputStream = new FileOutputStream("output.txt"); 
Writer writer = new OutputStreamWriter(outputStream); 

writer.write("data"); 

writer.close(); 

而不是寫一個字符串,您可以使用掃描儀對您的inputStream

Scanner sc = new Scanner(inputStream); 
while (sc.HasNext()) 
    //read using scanner methods 
+1

當OP提到'.txt'文件時,該解決方案有兩個主要的不便之處:1.'掃描器'會取消分隔符; 2.'Writer'中沒有指定編碼。所以,你會放棄換行符(因爲這是'Scanner'的默認分隔符),並且你可能不會使用正確的編碼,因爲你接收到的是字節而不是字符。關於後一個問題的更多細節[這裏](http://fgaliegue.blogspot.com/2014/03/strings-characters-bytes-and-character.html)。 – fge

2

如果你不上的Java 7和可不使用fge的解決方案,您可能想要將您的OutputStream包裝在BufferedOutputStream中

BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream("xx.txt")); 

這樣緩衝輸出流將以塊爲單位向文件寫入字節,這比每字節寫入字節更有效。

相關問題