java IO流

2023-12-18 13:29:52

流的分类

1、按照读写的方向来讲分为输入流和输出流。
2、按照读写内容的单位来讲分为字节流和字符流。
3、按照流的功能不同分为节点流和处理流。 节点流:直接连接在文件上的 处理流:套在其他流上的

流的体系

输入输出
字节流InputStreamOutputStream
字符流ReaderWriter

4个祖宗: InputStream OutputStream Reader Writer

以上都属于抽象类,所以不能直接使用,使用其子类

文件类: FileInputStream, 文件字节输入流 FileOutputStream,文件字节输出流 FileReader, 文件字符输入流 FileWriter, 文件字符输出流

字节流

  • 注意事项:流使用完成之后关闭流,写入操作的时候需要刷新一下。

  • 写入的时候默认是将文件内容清空之后进行写入的,第二个参数可以不把原文件内容清空,如下FileOutputStream fos = new FileOutputStream(new File("a.txt"), true);

读取:FileInputStream

public class TestFileInputStream {
 ? ?public static void main(String[] args) throws IOException {
 ? ? ? ?// 创建流
 ? ? ? ?FileInputStream fis = new FileInputStream(new File("a.txt"));
 ? ? ? ?/**TODO
 ? ? ? ? *  int a = fis.read();
 ? ? ? ? *  用来读取一个字节,返回的是Ascii码,注意不能用来读中文的一个字,因为一个汉字是两个字节
 ? ? ? ? *  System.out.println((char)a);
 ? ? ? ? *  --------------------------------
 ? ? ? ? *  byte[] bs = new byte[1024];
 ? ? ? ? *  int a = fis.read(bs); // 因为read返回的是ascii码传入一个byte数组,则可以用来吧byte数组读满
 ? ? ? ? *  System.out.println(new String(bs, 0, a)); // byte数组与String之间可以进行转换
 ? ? ? ? * **/
 ? ? ? ?// 读取文件最重要的一套写法
 ? ? ? ?byte[] bs = new byte[1024];
 ? ? ? ?int len = 0;
 ? ? ? ?while((len=fis.read(bs)) != -1){
 ? ? ? ? ? ?String a = new String(bs, 0, len);
 ? ? ? ? ? ?System.out.println(a);
 ? ? ?  }
 ? ? ? ?fis.close();
 ?  }
}

写入:FileOutputStream

public class TestFileOutputStream {
 ? ?public static void main(String[] args) throws IOException {
 ? ? ? ?FileOutputStream fos = new FileOutputStream(new File("a.txt"), true);
 ? ? ? ?fos.write("我知道我很帅".getBytes());
 ? ? ? ?// 好习惯
 ? ? ? ?fos.flush();// 刷新 保证数据的完整性
 ? ? ? ?fos.close();// 关闭 避免资源的浪费
 ?  }
}

字符流

  • 注意事项:流使用完成之后关闭流,写入操作的时候需要刷新一下。

  • 写入的时候默认是将文件内容清空之后进行写入的,第二个参数可以不把原文件内容清空,如下FileWriter?fos = new FileWriter(new File("a.txt"), true);

读取:FileReader

public class TestFIleReader {
 ? ?public static void main(String[] args) throws IOException {
 ? ? ? ?FileReader fr = new FileReader(new File("a.txt"));
// ? ? ?  int i = fr.read(); // 以字符为单位
// ? ? ?  System.out.println((char)i);
?
// ? ? ?  char[] cs = new char[1024];
// ? ? ?  int len = fr.read(cs);
// ? ? ?  System.out.println(new  String(cs, 0, len));
 ? ? ? ?char[] cs = new char[1024];
 ? ? ? ?int len = 0;
 ? ? ? ?while((len = fr.read(cs)) != -1){
 ? ? ? ? ? ?System.out.println(new String(cs, 0, len));
 ? ? ?  }
 ? ? ? ?fr.close();
 ?  }
}

写入:FileWriter

public class TestFileWriter {
 ? ?public static void main(String[] args) throws IOException {
 ? ? ? ?FileWriter fw = new FileWriter(new File("a.txt"), true);
 ? ? ? ?fw.write("a.txt");
 ? ? ? ?fw.flush();
 ? ? ? ?fw.close();
 ?  }
}

流的选择

字符流:读取文件中的文字信息
字节流:读取非文本文件的时候

文章来源:https://blog.csdn.net/qq_64468032/article/details/135060222
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。