I/O流

来源:互联网 发布:易语言网络爬虫 编辑:程序博客网 时间:2024/06/08 14:33

一:I/O体系


字节流:用于读写二进制数据,按字节来处理。

字符流:用于读写文本类数据,按Unicode字符来处理。

InputStream,OutputStream,Reader,writer都是抽象类。


二:字节流与字符流的区别


缓冲区可以简单地理解为一段内存区域


举例说明:

1,使用字节流不关闭执行

public class Demo {public static void main(String[] args) throws IOException { File file = new File("src/input.txt"); //打开个文件     OutputStream out = new FileOutputStream(file);                String str = "Hello World!";           byte b[] = str.getBytes();  // 字符串转byte数组         out.write(b); // 将字符串输出到文本                            // out.close();  不关闭输出流                     }}

结果:



2,使用字符流不关闭执行

public class Demo {public static void main(String[] args) throws IOException { File file = new File("src/input.txt"); //打开个文件 Writer out =new FileWriter(file);                String str = "Hello World!";           out.write(str); // 将字符串输出到文本                        //     out.close();  //不关闭输出流                     }}
结果:



强制性清空缓冲区:

public class Demo {public static void main(String[] args) throws IOException { File file = new File("src/input.txt"); //打开个文件 Writer out =new FileWriter(file);                String str = "Hello World!";           out.write(str); // 将字符串输出到文本             out.flush();//     out.close();  //不关闭输出流                     }}
结果:



三:常用的I/O流类

1,文件流

a,字节流:FileInputStream,FileOutputStream

b,字符流:FileReader,FileWriter


2,缓存流

a,字节流:BufferedInputStream,BufferedOutputStream

b,字符流:BufferedReader,BufferedWriter

BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));/*读*/


3,字符流与字节流之间的转换

a,OutputStreamWriter把Unicode字符流转换为字节流

b,InputStreamReader字节流转换为Unicode字符流

如:

BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"),"UTF-8"));
BufferedReader in = new BufferedReader(new InputStreamReader(system.in);/*键盘输入*/


4,输出流

a、字符流:PrintWriter

b、字节流:PrintStream

PrintStream ps=new PrintStream(socket.getOutputStream());/*写*/
PrintWriter pw=new PrintWriter(socket.getOutputStream());/*写*/

1 0