转换流

解决不同编码时会出现乱码的问题。代码的编码方式和被读文件的编码方式不对应。

字符输入转换流InputStreamReader

IO流:转换流、打印流_字符输入

public class InputStreamReaderTest2 {
    public static void main(String[] args) {
        try {
            // 1. 得到文件的原始字节流(GBK的字节流形式)
            InputStream is = new FileInputStream("io-app2/src/a06.txt");
            // 2. 把原始的字节输入流转换成指定字符编码的字符输入流
            Reader isr = new InputStreamReader(is, "GBK");
            // 3. 把字符输入流包装成缓冲字符输入流
            BufferedReader br = new BufferedReader(isr);
            
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

字符输出转换流OutputStreamWrite

IO流:转换流、打印流_字符输入_02

IO流:转换流、打印流_System_03

打印流

PrintStream(字节输出流下的实现类)、PrintWrite(字符输出流下的实现类)

作用:可以更方便高效打印数据出去,实现打印什么出去就出去什么。

IO流:转换流、打印流_System_04

class PrintTest {
    public static void main(String[] args) {
        try {
            // 创建一个打印流
             //PrintStream ps = new PrintStream("io-app2/src/a08.txt", Charset.forName("GBK"));
            // PrintStream ps = new PrintStream("io-app2/src/a08.txt");
            PrintWriter ps =
                new PrintWriter(new FileOutputStream("io-app2/src/a08.txt", true));

            ps.println(97);
            ps.println('a');
            ps.println("我爱你中国abc");
            ps.println(true);
            ps.println(99.5);

            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

IO流:转换流、打印流_System_05

在打印上面这两个没有什么区别,可以随便用。

输出语句的重定向

当程序设置好,上线之后是没有控制台的,所以想要显示内容,需要重新定向,使用setOut方法。

public class PrintTest2 {
    public static void main(String[] args) {
        System.out.println("君兮若俦");
        System.out.println("苟在千里");

        try {
            PrintStream ps = new PrintStream(new FileOutputStream("io-app2/src/a09.txt"));
            // 把系统默认的打印流对象改成自己设置的打印流
            System.setOut(ps);

            System.out.println("强主攘年");
            System.out.println("忙心不已");

            ps.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}