一、IO流
IO流:存储和读取数据的解决方案
IO流的作用:用于读写数据(本地文件和网络文件)
IO流按流向可以分为输出流(程序–>文件)和输入流(文件–>程序)
程序到文件为输出,文件到程序为输入,参照物为程序
IO流按操作文件的类型可以分为:
①字节流,可以操作所有类型的文件。
②字符流,只能操作纯文本文件(能用windows自带记事本打开并且能读懂的文件)
字节流的应用场景:拷贝文件
字符流的应用场景:文本文件的读和写
二、字节流
1.往文件中写入数据
①创建对象:FileOutputStream f = new FileOutputStream (File对象或字符串)
字符串表示的路径的如果文件不存在会自动创建一个文件,但要保证该文件的父级路径存在
如果文件已经存在则会清空文件中的数据
②f.write()写入内容,写入的是对应的ASCII码代表的字符
③f.close()释放资源,如果不释放则文件一直处于被占用的状态,无法对文件进行某些操作
把一段字符串写入文件中
File file = new File("c:\\aaa\\a.txt");
FileOutputStream f1 = new FileOutputStream(file);
String s ="abcdefg";
byte[] arr = s.getBytes();
f1.write(arr);
f1.close();
换行输入(在需要换行的地方写入\r\n)
File file = new File("c:\\aaa\\a.txt");
FileOutputStream f1 = new FileOutputStream(file);
String s1 ="abcdefg";
byte[] bytes1 = s1.getBytes();
f1.write(bytes1);
String s3 ="\r\n";
byte[] bytes3 = s3.getBytes();
f1.write(bytes3);
String s2 = "123";
byte[] bytes2 = s2.getBytes();
f1.write(bytes2);
f1.close();
续写文件内容
FileOutputStream f1 = new FileOutputStream(file,true);
在创建对象时加上true,默认为false
2.从文件中读取数据
FileInputStream i1 = new FileInputStream(file);
int b;
while ((b=i1.read())!=-1){
System.out.println((char) b);
}
f1.close();
read读取一个字符,移动一次指针,所以要用一个中间变量来接收read的返回值,不能重复使用read
此方法只能读取一个字符对应的ASCII码
如果file对应的路径不存在,直接报错
如果读到末尾返回-1
3.文件拷贝
FileInputStream f1 = new FileInputStream("c:\\aaa\\a.txt");
byte[] bytes = new byte[3];
int r1 = f1.read(bytes);//返回读取的字节数
System.out.println(r1);
String s = new String(bytes);
System.out.println(s);
f1.close();
使用这种方法可能会出现错误,如:读取abcde,创建的byte的数组的长度为2,第一次读取ab,第二次读取cd,第三次读取ed,因为读取过程是不断覆盖数组中原有内容的过程,第二次读取会把第一次读取到的ab覆盖,第三次读取时只剩下一个e,e将c覆盖后没有元素取覆盖d,所以返回的元素是ed
避免读到最后一段数据时长度小于3而显示错误的数据,可以
String s = new String(bytes,0, r1);
从0索引开始往后读r1个数据
FileInputStream f1 = new FileInputStream("c:\\aaa\\a.txt");
FileOutputStream f2 = new FileOutputStream("c:\\aaa\\data.txt");
byte[] bytes = new byte[4];
int r = 0;
while((r=f1.read(bytes))!=-1){//返回读取的字节数
f2.write(bytes,0,r);
}
f2.close();
f1.close();