JAVA-IO(2)操作简介

xiaoxiao2021-02-28  102

Java IO操作主要指的是使用Java进行输入输出操作,Java的所有操作类都早Java.io包中,在使用时需要导入此包.

上篇博文讲了File,字节流和字符流.

http://blog.csdn.net/haiyang_duan/article/details/76769025

紧接着,讲解其他的流.

一. 转换流OutputStreamWriter与InputStreamRreader

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

String path = "C:" + File.separator + "test"; Writer out = null; out = new OutputStreamWriter(new FileOutputStream(path)); out.write("hello!"); out.close();

同理,上述代码稍作修改可用于将字节输入流转换为字符输入流,就不在演示.

提示:FileWriter和FileReader的说明 FileOutputStream是OutputStream的直接子类 FileIutputStream是IutputStream的直接子类 而,FileWriter并非Writer的直接子类,是OutputStreamWriter的直接子类, FileReader并非Reader的直接子类,是InputStreamRreader的直接子类, 可见,不管使用字节流还是字符流,最终都是以字节流的形式操作输入输出.

二. 内存操作流ByteArrayOutputStream与ByteArrayInputStream

//内存输入输出流 String str = "HELLOWORLD"; ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int temp = 0; while((temp=bis.read())!=-1){ char c = (char) temp; bos.write(Character.toLowerCase(c)); } String string = bos.toString(); bis.close(); bos.close(); System.out.println(string);

三. 管道流PipedOutputStream与PipedInputStream

四. 打印流PrintStream与PrintWriter

在打印流的构造方法中,有一个可以直接接收OutputStream对象,这是因为,与OutputStream相比,PrintStream可以更加方便的输出数据,这就好像将OutputStream重新包装了一下,使之输出更加方便.这样的设计成为装饰设计模式.

使用PrintStream输出

String path = "C:" + File.separator + "test"; PrintStream ps = null; ps = new PrintStream(new FileOutputStream(path)); ps.print("hello "); ps.println("world!"); ps.close();

使用打印流进行格式化

转载请注明原文地址: https://www.6miu.com/read-51228.html

最新回复(0)