【1】文件
1. 文本文件【存储字符】
2. 二进制文件【存储字节】
【2】针对文件内容的读写,分为两个系列
1. 字节流对象
针对二进制文件,以字节为单位进行读写
读:InputStream【既可针对普通文件,又可针对特殊文件(网卡,socket文件)进行读写】 ----> 该类为抽象类,往往使用子类 FileInputStream【特指针对普通文件进行读写】
public class Demo01 {//一次读一个字节 public static void main(String[] args) throws IOException { //创建对象的同时,输入要打开文件的路径 InputStream i = new FileInputStream("d:/test.txt"); while(true) { //一个字节一个字节的读文件 int b = i.read(); //如果读到了-1,就说明读到了文件末尾 if (b == -1) { break; } System.out.println(b);//文件读取的结果是ASCII码值 } //读完之后要去关闭文件,释放资源 i.close(); } }
public class Demo02 {//一次读若干个字节 public static void main(String[] args) throws IOException { InputStream i = new FileInputStream("d:/test.txt"); while(true){ byte[] buffer = new byte[1024];//需要创造一个容器来存放读到的内容 int len = i.read(buffer);//把读到的内容放入buffer数组中 if(len==-1){ //文件已经读完 break; } for (int j = 0; j < len; j++) { System.out.println(buffer[j]); } } i.close(); } }
写:OutputStream 【既可针对普通文件,又可针对特殊文件(网卡,socket文件)进行读写】 ----> 该类为抽象类,往往使用子类 FileOutputStream【特指针对普通文件进行读写】
public class Demo03 {//一个字节一个字节的写 public static void main(String[] args) throws IOException { OutputStream o = new FileOutputStream("d:/test.txt"); o.write(97); o.write(98); o.write(65); } }
public class Demo04 {//一次写若干个 public static void main(String[] args) throws IOException { OutputStream o = new FileOutputStream("d:/test.txt"); byte[] buffer = new byte[]{66,67,68}; o.write(buffer); o.close; } }
【上述写操作,会清空原有内容】
2. 字符流对象
针对文本文件,以字符为单位进行读写
读:Reader【既可针对普通文件,又可针对特殊文件(网卡,socket文件)进行读写】 ----> 该类为抽象类,往往使用子类 FileReader【特指针对普通文件进行读写】
public class Demo05 {//字符流文件的读 public static void main(String[] args) throws IOException { Reader r = new FileReader("d:/test.txt"); while(true){ char[] buffer = new char[1024]; int len = r.read(buffer); if(len==-1){ break; } for (int i = 0; i < len; i++) { System.out.println(buffer[i]); } } r.close(); } }
写:Writer【既可针对普通文件,又可针对特殊文件(网卡,socket文件)进行读写】 ----> 该类为抽象类,往往使用子类 FileWriter【特指针对普通文件进行读写】
public class Demo06 { public static void main(String[] args) throws IOException {//字符流文件的写 Writer w = new FileWriter("d:/test.txt"); w.write("asdfg"); w.close(); } }
3. 在操作系统中,通过路径来描述文件的具体位置
绝对路径:以盘符开头 D:\ChromeCore\update
相对路径:以 . 或者 .. 开头 ,其中 . 表示当前路径 ,.. 表示当前路径的父路径
从基准路径出发,按照相应的规则寻找路径。
4. java中操作文件的分类
1)文件系统相关操作【 指的是通过" 文件资源管理器 " 能够完成的一些功能】
java提供了一个File类来描述文件/目录~
1))列出有哪些文件;
2))创建文件;
3))创建目录;
4)) 删除文件;
5))重命名文件;
方法
2))文件内容相关操作
打开文件;创建对象时,输入文件路径,即可打开文件
读文件;read()
写文件;write()
关闭文件;close()
5. 文件操作案例
1) 扫描指定目录,找到名称中包含指定字符的所有普通文件,并询问用户是否要删除