字符输出输入流转换为字节输出输入流

文章详细介绍了Java中InputStreamReader、OutputStreamWriter等处理字节输入流和字符输出流的方式,以及PrintStream和System.lineSeparator在输出控制中的应用。
摘要由CSDN通过智能技术生成

 字节输入流转字符输出流

 try(InputStreamReader inputStreamReader =
                    new InputStreamReader(new FileInputStream("io/in.txt"));
            InputStreamReader inputStreamReader1 =
                    new InputStreamReader(new FileInputStream("io/csb_gbk.txt"), "GBK");
            InputStreamReader inputStreamReader2 =
                    new InputStreamReader(new FileInputStream("io/in.txt"), Charset.forName("GBK"));) {
            System.out.println(inputStreamReader.getEncoding()); // UTF8
            System.out.println((char) inputStreamReader.read());
            System.out.println((char)inputStreamReader1.read());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

字节输出流转字符输出流

 try (OutputStreamWriter outputStreamWriter =
                     new OutputStreamWriter(new FileOutputStream("io\\001.txt"), Charset.forName("utf-8"));) {
            System.out.println(outputStreamWriter.getEncoding());
            outputStreamWriter.write("放票了" + System.lineSeparator());
            outputStreamWriter.write("没抢到" + System.lineSeparator());
            outputStreamWriter.write("加入候补了" + System.lineSeparator());
            outputStreamWriter.write("等待中ing..." + System.lineSeparator());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

 System.lineSeparator()换行

 try (PrintStream printStream = new PrintStream(new File("io\\print.txt"));) {
            printStream.printf("余票还有%d", 12);
            System.setOut(printStream);
            System.out.print("今天天气不错");
            System.out.println();
            System.out.printf("余票还有%d", 12);
            System.out.println();
            System.out.print("123");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        System.out.println("hello");
        System.err.println("hello");

 System.setOut(printStream);

在此之后try块中的输入都会写入目标文件

块外的不输出也不输入文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值