字节输入流转字符输出流
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块中的输入都会写入目标文件
块外的不输出也不输入文件