程序输出java.io.PrintStream@3f3afe78是咋回事


import java.io.*;

public class Solution {
    public static TestString testString = new TestString();

    public static void main(String[] args) throws  IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String name = reader.readLine();

        FileOutputStream fox = new FileOutputStream(name);

        PrintStream consoleStream = System.out;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintStream stream = new PrintStream(outputStream);
        System.setOut(new PrintStream(fox));

        testString.printSomething();
        System.setOut(consoleStream);
        String r = stream.toString();
        System.out.println(r);

        fox.flush();
        fox.close();
        reader.close();

    }

    public static class TestString {
        public void printSomething() {
            System.out.println("这是用于测试的文本12345");
        }
    }
}


这是一个将printSomething()方法中的内容写入控制台输入的文件地址中,并在控制台显示输出的程序,写入没有问题,显示输出却显示的是 :java.io.PrintStream@3f3afe78;并非计划中的:这是用于测试的文本12345。

这个是为什么,要咋改正。

String r = stream.toString();
不能这么写
byte[] bytes = new byte[stream.available()];
stream.read(bytes);
String r = new String(bytes);

上面代码逻辑有些看不懂,为什么要用FileOutputStream,而且PrintStream要用两个

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(outputStream, true, "utf-8");
        ps.print("这是用于测试的文本12345");

        String content = outputStream.toString("utf-8");

        System.out.println("content="+content);