2012-01-25 60 views
5

我有一個字符串數組(實際上它是一個ArrayList),我想從它創建一個InputStream,數組中的每個元素都是流中的一行。如何從字符串數組創建一個InputStream

我該如何以最簡單和最有效的方式做到這一點?

+0

我從回調中獲取數組,並希望將其作爲ZipEntity(因此是InputStream)添加到zip文件中。我也想到了StringBuilder方法,但我希望會有一些更好的(一些InputStream包裝)方法來做到這一點... – zacsek

回答

6

您可以使用StringBuilder並在其間用換行符附加所有字符串。然後創建一個使用

new ByteArrayInputStream(builder.toString().getBytes("UTF-8"));

我使用UTF-8在這裏輸入流,但您可能需要使用不同的編碼,取決於您的數據和要求。

另請注意,您可能必須包裝該輸入流才能逐行讀取內容。

但是,如果您不必使用輸入流只是迭代字符串數組,可能會使easiert編碼並更容易維護解決方案。

0

最簡單的可能是將它們粘在一起,並將結果的String傳遞給StringReader。

0

更好的方法是使用BufferedWriter類。 有一個樣本:

try { 
    List<String> list = new ArrayList<String>(); 
    BufferedWriter bf = new BufferedWriter(new FileWriter("myFile.txt")); 

    for (String string : list) { 
     bf.write(string); 
     bf.newLine(); 
    } 

    bf.close(); 
} catch (IOException ex) { 
} 
2

你可以嘗試使用類ByteArrayInputStream的,你可以給一個字節數組。但首先你必須將List轉換爲一個字節數組。嘗試以下操作。

List<String> strings = new ArrayList<String>(); 
    strings.add("hello"); 
    strings.add("world"); 
    strings.add("and again.."); 

    StringBuilder sb = new StringBuilder(); 
    for(String s : strings){ 
     sb.append(s);   
    } 

    ByteArrayInputStream stream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); 
    int v = -1; 
    while((v=stream.read()) >=0){ 
     System.out.println((char)v); 
    } 
相關問題