文件读写:字节流与字符流详解 (文件io)
1.文件内容操作java 提供了一系列类表示流对象1)字节流:以字节为基本单位进行读写2)以字符为基本单位进行读写2.⽂件内容的读写⸺字节流字节流的核心类2.1InputStreamInputStream 是抽象类,无法创建出具体的 实例. 抽象类会有抽象方法,没有定义,只有声明.抽象类存在的意义,就是为了被扩展(继承)上述抽象类, 在标准库里已经被创建好了子类,FileInputStream.从文件中读取数据FileInputStream构造方法签名说明FileInputStream(File file)利⽤ File 构造⽂件输⼊流FileInputStream(String name)利⽤⽂件路径构造⽂件输⼊流方法修饰符及返回值类型⽅法签名说明intread()读取⼀个字节的数据返回 -1 代表已经完全读完了intread(byte[] b)最多读取 b.length 字节的数据到 b中返回实际读到的数量-1 代表以及读完了intread(byte[] b, int off, int len)最多读取 len - off 字节的数据到 b 中放在从 off 开始返回实际读到的数量-1 代表以及读完了voidclose()关闭字节流代码示例import java.io.FileInputStream; import java.io.IOException; //使用字节流 public class demo { public static void main(String[] args) throws IOException { FileInputStream inputStream new FileInputStream(./1.txt); //通过 read 方法读取数据 while (true){ int data inputStream.read(); if(data-1){ //读到文件末尾 break; } //打印数据 System.out.printf(%x\n,data); } while(true){ byte[] bytes new byte[1024]; int n inputStream.read(bytes); if(n-1){ break; } for (int i 0; i n; i) { System.out.printf(0x%X\n,bytes[i]); } } //关闭文件 inputStream.close(); } }计算机中,读取硬盘,比读取内存,更低效.一次读一个字节,分N次读完(多次硬盘操作). 一次读NG字节,一次读完(一次硬盘读取) 效率可能差异很大~~try-with-resources 语法import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class demo8 { public static void main(String[] args) { try(InputStream inputStream new FileInputStream(./1.txt)){ while(true){ byte[] bytes new byte[1024]; int n inputStream.read(bytes); if(n-1){ break; } for (int i 0; i n; i) { System.out.printf(0x%x\n,bytes[i]); } } //close 不必写了 //会在try 结束的时候,自动调用 }catch (IOException e){ e.printStackTrace(); } } }try-with-resources语法要求写在括号里的资源需要实现 AutoCloseable 或 Closeable 接口FileInputStream 满足该条件无论 try 代码块正常运行结束还是中途抛出异常终止系统都会自动调用资源的 close () 方法关闭流无需我们在 finally 中手动编写关闭流的代码既简化了代码又能避免因忘记关闭流引发的文件资源占用与内存泄漏问题。2.2 OutputStream和InputStream类似OutputStream 同样只是⼀个抽象类要使⽤还需要具体的实现类。我们现在还是只关⼼写⼊⽂中所以使⽤FileOutputStreamFileOutputStream方法修饰符及返回值类型⽅法签名说明voidwrite(int b)写⼊要给字节的数据voidwrite(byte[] b)将 b 这个字符数组中的数据全部写⼊ os 中intvoidwrite(byte[] b, int off,int len)将 b 这个字符数组中从 off 开始的数据写⼊ os 中⼀共写 len 个voidclose()关闭字节流voidflush()代码示例import javax.imageio.IIOException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class demo9 { public static void main(String[] args) { try(OutputStream outputStream new FileOutputStream(./1.txt)){ outputStream.write(97); outputStream.write(98); outputStream.write(99); }catch (IIOException e){ e.printStackTrace(); } catch (IOException e) { throw new RuntimeException(e); } } }默认情况下, 使用OutputStream 打开文件,就会清空文件内容(操作系统原生api就是这样的)OutputStream outputStream new FileOutputStream(./1.txt,true)追加写,来解决3.⽂件内容的读写⸺字符流Reader FileReaderWriter FileWriter类似字节流1)打开文件2)读/写(字符为单位)3)关闭(通过try with resource)