正如标题所说,我希望每行(每System.out.print
)存储一个数组/ arrayList。
到目前为止,我已经尝试ByteArrayOutputStream
,但它只将所有内容都附加到一个对象中。如有必要,我很乐意发布代码片段。对不起noob问题
编辑代码:
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
内的值但没有运气的东西。
答案 0 :(得分:0)
根据您发布的代码,我做了一些修改,看看这是否是您要找的。 p>
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