1.文件内容操作
java 提供了一系列类表示流对象
1)字节流:以字节为基本单位进行读写
2)以字符为基本单位进行读写
2.⽂件内容的读写⸺字节流
字节流的核心类
2.1InputStream
InputStream 是抽象类,无法创建出"具体的" 实例. 抽象类会有抽象方法,没有定义,只有声明.抽象类存在的意义,就是为了被扩展(继承)
上述抽象类, 在标准库里已经被创建好了子类,FileInputStream.从文件中读取数据
FileInputStream
构造方法
签名 | 说明 |
| FileInputStream(File file) | 利⽤ File 构造⽂件输⼊流 |
| FileInputStream(String name) | 利⽤⽂件路径构造⽂件输⼊流 |
方法
修饰符及返回值类型 | ⽅法签名 | 说明 |
| int | read() | 读取⼀个字节的数据,返回 -1 代表 已经完全读完了 |
| int | read(byte[] b) | 最多读取 b.length 字节的数据到 b 中,返回实际读到的数量;-1 代表 以及读完了 |
| int | read(byte[] b, int off, int len) | 最多读取 len - off 字节的数据到 b 中,放在从 off 开始,返回实际读 到的数量;-1 代表以及读完了 |
| void | close() | 关闭字节流 |
代码示例
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 同样只是⼀个抽象类,要使⽤还需要具体的实现类。我们现在还是只关⼼写⼊⽂中,所以使⽤FileOutputStream
FileOutputStream
方法
修饰符及返回值类型 | ⽅法签名 | 说明 |
| void | write(int b) | 写⼊要给字节的数据 |
| void | write(byte[] b) | 将 b 这个字符数组中的数据全部写 ⼊ os 中int |
| void | write(byte[] b, int off, int len) | 将 b 这个字符数组中从 off 开始的 数据写⼊ os 中,⼀共写 len 个 |
| void | close() | 关闭字节流 |
| void | flush() |
代码示例
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 FileReader
Writer FileWriter
类似字节流
1)打开文件
2)读/写(字符为单位)
3)关闭(通过try with resource)