2016-06-27 76 views
-1

如標題所示,我想按行存儲(每System.out.print)存儲在array/arrayList中。 到目前爲止,我已嘗試ByteArrayOutputStream,但它只能將所有內容附加到一個對象中。如果有必要,我很樂意發佈代碼片段。很抱歉的小白問題將控制檯每行輸出存儲在一個數組中

編輯代碼:

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
PrintStream ps = new PrintStream(baos); 
PrintStream old = System.out; 
String[] str= new String[10]; 

System.setOut(ps); 

for(int x=0;x<str.length;x++){ 
ps.println("Test: "+x); 
str[x] = baos.toString(); 
} 
System.out.flush(); 
System.setOut(old); 
for(int x=0;x<str.length;x++){ 
System.out.println(str[x]); 
} 

輸出:

Test: 0 

Test: 0 
Test: 1 

Test: 0 
Test: 1 
Test: 2 

Test: 0 
Test: 1 
Test: 2 
Test: 3 

Test: 0 
Test: 1 
Test: 2 
Test: 3 
Test: 4 

Test: 0 
Test: 1 
Test: 2 
Test: 3 
Test: 4 
Test: 5 

Test: 0 
Test: 1 
Test: 2 
Test: 3 
Test: 4 
Test: 5 
Test: 6 

Test: 0 
Test: 1 
Test: 2 
Test: 3 
Test: 4 
Test: 5 
Test: 6 
Test: 7 

Test: 0 
Test: 1 
Test: 2 
Test: 3 
Test: 4 
Test: 5 
Test: 6 
Test: 7 
Test: 8 

Test: 0 
Test: 1 
Test: 2 
Test: 3 
Test: 4 
Test: 5 
Test: 6 
Test: 7 
Test: 8 
Test: 9 

我想什麼有str陣列是這樣的:

str[0] = "Test: 0" 
str[1] = "Test: 1" 
str[2] = "Test: 2" 
str[3] = "Test: 3" 
str[4] = "Test: 4" 
str[5] = "Test: 5" 
str[6] = "Test: 6" 
str[7] = "Test: 7" 
str[8] = "Test: 8" 
str[9] = "Test: 9" 

我也尋找像刪除ByteArrayOutputStream中的值但是n好運。

+2

請添加您嘗試過的代碼?你的意見是什麼?你想要什麼輸出? – thegauravmahawar

+0

將輸出重定向到文件 –

回答

0

根據你發佈的代碼,我做了一些修改,看看你是否在尋找這個。

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
PrintStream ps = new PrintStream(baos); 
PrintStream old = System.out; 
String[] str= new String[10]; 

System.setOut(ps); 

for(int x=0;x<str.length;x++){ 
ps.println("Test: "+x); 
str[x] = baos.toString(); 
baos.reset(); 
} 
System.out.flush(); 
System.setOut(old); 
for(int x=0;x<str.length;x++){ 
System.out.println(str[x]); 
} 

訣竅是,每行str[x] = baos.toString()執行時的時間,累計輸出仍然存在,所以你需要使用reset()放棄積累數據,爲更多細節reset(),請參考官方文檔here

+0

非常感謝!這對我有效。 :) – Daniel

相關問題