File类
File类是对文件操作的类。
1.1目录分隔符
在windows和非windows系统,目录分隔符是不同的:
windows:采用\
非windows:采用/
1.2路径的分类
绝对路径:从磁盘的根目录开始,一级一级直到找到这个文件
C:/Users/admin/Desktop/abc.txt
相对路径:以某一个文件作为参照,相对于这个文件的路径
abc.txt
1.3常用的属性
- static String pathSeparator(static char pathSeparatorChar)->路径分隔符,分隔两个路径
- static String separator (static char separatorChar) -> 目录分隔符,用来分隔两级目录
IO流的分类
按照方向:输入流和输出流
按照单位:字节流和字符流
InputStream 、 OutputStream
InputStream:字节输入流
OutputStream:字节输出流
字节流:
1.1文件字节输入流的创建与关闭
InputStream ins = new FileInputStream("file\\a.txt");
ins.close();
1.2流中的内容读取
- read(byte[] array)
- 从流中读取数据,将读取到的内容填充到Array中
- 返回值表示,本次从流中读取了多少字节的内容
- 如果返回值为-1,表示本次没有读取到任何内容,说明流中已经没有数据了。
- read(byte[] array, int offset, int length)
- 从流中读取数据,并将读取到的数据填充到数组array的指定位置处、
- 返回值表示,本次从流中读取到了多少字节的内容
- 如果返回值为-1,表示本次没有读取到任何内容,说明流中已经没有数据了。
- read()
- 返回值是一个int,用力爱表示读取到的一个字节。
1.3将数据写入到文件
如果实例化输出流的目标文件不存在,执行程序写数据的时候,会自动创建这个文件。
outputStream ops = new FileOutputStream("file\\b.txt");
ops.write(array, 0, length);
案例:
InputStream ins = null;
OutpuStream ops = null;
try{
//实例化一个流对象,用来连接文件和内存
ins = new FileInputStream("file\\a.txt");
//参数中的boolean值代表是否在文件末尾拼接(false会发生覆盖)
ops = new OutputStream("file\\b.txt", true);
byte[] array = new byte[1024];
//记录每次读取到多少数据,如果length值为-1,表示没有读到数据
int length = 0
while((length = ins.read(array)) != -1){
//将读到数组中的内容,写到目标文件中
ops.write(array, 0, length);
//清空缓存数据
ops.flush();
}
}catch(IOException e){
e.printStackTrace();
}finally{
//一般情况下,流的关闭,都是放在finally中执行的
if(ins != null){
try{
ins.close();
}catch(IOException e){
e.printStackTrace();
}
}
if(ops != null){
try{
ops.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
字符流:
字符流是按照字符来读取的,字符输入流和字符输出流的类分别是:Reader、Writer
数据的读取
- read()
- 每次从流中读取一个字符,并将读取到的字符转为一个整型返回
- 如果返回值为-1,表示流中已经没有数据了
- read(char[] array)
- 每次从流中读取到的字符存入array数组
- 返回每次读取到了多少个字符
- 如果返回-1,说明流中已经没有数据了
代码示例:
Reader:
//此时try中括号里面实例化的reader对象,只能在try代码段中使用,并且使用结束后,会自动进行流关闭
//try小括号中的内容不是随便写的,只有AutoClosable接口的实现类可以在try的小括号里声明和实例化
try(Reader reader = new FileReader("C:/a.txt")){
int data = 0;
while((data = reader.read()) != -1){
System.out.print(char(data));
}
}catch (IOException e){
e.printStackTrace();
}
Writer:
try(Writer writer = new FileWriter("file\\a.txt", true)){
writer.write("hello world");
}catch(IOException e){
e.printStackTrace();
}