File类
在与文件交互的过程中,大部分读取结束的返回值都为-1 ,目前只有String readLine()会返回null
- 返回-1 读取全部文件读取完毕
- 返回null 读取此行文件读取完毕
简单关键词了解:
- file: 文件
- directory: 文件夹/目录
- path: 路径
分隔符与换行符:每个系统底层实现不太一样,可以通过Java内置的方法获取该系统的指定符号。从而提高Java系统的健壮性与可移植性等。
System.lineSeparator();
//获取系统相对应的换行符
String pathSeparator = File.pathSeparator;
//获取路径分隔符 windows -> ; liunx -> :
String separator = File.separator;
//获取文件路径符 windows -> \ liunx -> /
File f3 = new File("D:\\123\\新建文件夹");
f3.delete(); //此方法删除不会放入回收站,需谨慎操作
例:文件搜索
查找指定路径下格式为【.Java】的文件,找到之后,打印其绝对路径。
思路:
路径中可能有文件夹也可能有文件。我们不止要查询表面的文件,还要搜寻在文件夹内部的文件资源,在这个时候,最好用的方法应该就是递归了
插一嘴递归的广告:明白两点,会更利于递归的使用
- 要清楚获得什么
- 要清楚在哪里结束
我们在这里要得到的是查找指定格式的文件路径,当我们搜索完该文件夹中的全部内容时。就要结束了。由于我们要使用到递归,所以要把方法提取出来。
public class Demo03DiGui {
public static void main(String[] args) {
//File类并没有提供关于路径的getter 与setter方法.
//我们只能通过其构造函数来设置
File dir = new File("D:\\下载");
printDir(dir);//调用方法
}
private static void printDir(File dir) {
//返回指定目录下所有文件和目录的绝对路径,这里应该先判断是否为空,
//如果数组为空,不仅里面的操作就是无用功,而且还可能出现异常
File[] files = dir.listFiles();
//使用增强for遍历数组
for (File file : files) {
//判断是不是文件
if (file.isFile()){//如果是文件
//判断否和格式要求吗
if(file.toString().toLowerCase().endsWith(".java"){
//如果符合格式要求,就输出其绝对路径
System.out.println(file.getAbsolutePath());
}
}else {//如果不是文件
//调用自身,来查找当前路径下的文件夹中的内容
printDir(file);
}
}
}
}
File过滤器
实现流程图解
如果需要判断的文件路径中含有文件和文件夹,要在筛选文件的同时(根据使用前提选择是否让文件夹也能够通过),意味着: FileFilterImpl 的实现类中重写的accept中,返回值为true,反之即为flase.
使用File过滤器 + lambda表达式
public class Demo03DiGui {
public static void main(String[] args) {
File dir = new File("D:\\下载");
printDir(dir);
}
private static void printDir(File dir) { //lambda 表达式开始
File[] files = dir.listFiles(pathname->pathname.getAbsoluteFile().toString().endsWith(".java") || pathname.isDirectory()); //lambda 表达式结束,中间无换行
for (File file : files) {
if (file.isFile()){
System.out.println(file.getAbsolutePath());
}else {
printDir(file);
}
}
}
}
IO流
字符或者字节的写入读取,必须指定文件,不可以只有路径,否则会报错
标准缓存标准大小 8192
字节流
文件字节写入(输出)
单行字符写入
import java.io.FileOutputStream;//这三条语句都有异常,抛出最大的异常即可
import java.io.IOException;public class Demo01OutputStream {
public static void main(String[] args) throws IOException {
//创建对象并指定地址(地址中没有这个文件,会自己new)
FileOutputStream fos = new FileOutputStream("D:\\123\\a.txt");
//写入指定数据
fos.write(97);
//关闭这个IO流
fos.close();
}
}
如果这个(D:\123\a.txt)这个文件已经存在,且已经有数据,那么文件中的舒服会被覆盖掉.
write中: 前一个字节为负数时,则会与第二个字节组成中文显示(查询系统默认码表)
数据追写(换行)
FileOutputStream fos = new FileOutputStream(“D:\123\a.txt”,true / flase); 追加还是覆盖
package com.yu.io;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo03OutputStream {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("D:\\123\\bdc.txt",false);
//覆盖写入到"D:\\123\\bdc.txt"
for (int i = 0; i < 10; i++) {
fos.write("你好".getBytes());
//字符串转换为数组写入到文件中
fos.write("\r\n".getBytes());
//windows 换行: \r\n
//linux 换行: \n
//mac 换行: \r
}
fos.close();
}
}
文件读取(输入)
字节读取
package com.yu.io;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Demo01InputStream {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\123\\c.txt");
ArrayList<Integer> i = new ArrayList<>();
int len =0;
while ((len = fis.read()) != -1){
System.out.print((char) len);
}
fis.close();
}
}
文件多字节读取
读取指定长度的字节,存储到数组中,
package com.yu.io;
import java.io.FileInputStream;
import java.io.IOException;
public class Demo02InputStream {
public static void main(String[] args) throws IOException {
//建立读取的通道
FileInputStream fis = new FileInputStream("D:\\123\\c.txt");
//建立数组来存放数据,起到缓冲作用
byte[] bytes = new byte[1024];
//记录读取的有效个数
int len;
//读取到文件末,返回-1退出循环读取
while ((len = fis.read(bytes)) != -1){
//把数组中的有效内容转换为字符串打印
System.out.println(new String(bytes,0,len));
}
//施放资源
fis.close();
}
}
读取原理
文件的复制
注意中文,汉字在不同的编码集中所占的字节会有不同
package com.yu.io;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo03IOputStream {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("D:\\123\\c.txt");
FileOutputStream fos = new FileOutputStream("D:\\123\\cc.txt",true);
int len;
while ((len = fis.read()) != -1) {
fos.write(len);
}
//流使用之后要记得关闭,释放资源。
fis.close();
fos.close();
}
}
字符流
写入,读取都是根据不同的角度来看待事物的一种叫法,
- 如果你是内存,把数据写入内存,就叫输入,
- 如果你是计算机,把数据写入内存,就叫输出。
读取(输入)
package com.yu.io.democharacter;
import java.io.FileReader;
import java.io.IOException;
public class Demo01Reader {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("D:\\123\\c.txt");
/* int len = 0;
while ((len = fr.read()) != -1) {
System.out.print((char) len);
}*/
char[] ch = new char[1024];
int len = 0;
while ((len = fr.read(ch))!=-1){
System.out.println(new String(ch,0,len));
}
fr.close();
}
}
写入(输出)
package com.yu.io.democharacter;
import java.io.FileWriter;
import java.io.IOException;
public class Demo03Writer {
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("D:\\123\\cc.txt", true);
for (int i = 0; i < 10; i++) {
fw.write("HelloWorld" + i + "\r\n");
fw.flush();
}
fw.close();
}
}
带换冲的流
读整行的数据时,返回值不会包括换行符
缓冲流当中的换行是newLine();
package com.yu.io.buffered;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo01BufferedOutputStream {
public static void main(String[] args) throws IOException {
FileOutputStream fis = new FileOutputStream("D:\\123\\01.txt",false);
BufferedOutputStream bos = new BufferedOutputStream(fis,2);
bos.write("我把数据写入到内部缓冲中".getBytes());
bos.write("缓冲冲冲冲中".getBytes());
bos.flush();
bos.close();
fis.close();
}
}
IO流异常的处理
DK 7 新特性处理
package com.yu.io.democharacter;
import javax.imageio.IIOException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo02TryCatch {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("D:\\123\\vip.png");
FileOutputStream fos = new FileOutputStream("D:\\123\\vip1.png", true);) {
byte[] bytes = new byte[1024];
int len;
while ((len = fis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
普通处理方法
package com.yu.io.democharacter;
import java.io.FileWriter;
import java.io.IOException;
public class Demo01TryCatch {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw = new FileWriter("D:\\123\\ccc.txt",false);
fw.write("String");
} catch (IOException e) {
System.out.println(e);
} finally {
if (fw!=null){
try {
fw.close();
}catch (IOException e){
System.out.println(e);
}
}
}
}
}
序列化与反序列化
写入类与读取类
想要被持久化,被实例化的类必须实现serializable序列化接口
writeObject();
readObject();
不能序列化static和transient修饰的成员变量
package com.yu.io.objet;
import java.io.*;
import java.util.ArrayList;
public class Exer01ObjectOutputStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
writeingObject();
readingObject();
}
private static void readingObject() {
Object o;
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\123\\person.txt"));) {
while ((o = ois.readObject()) != null) {
Person tmp = (Person) o;
System.out.println(tmp.toString());
}
} catch (EOFException e) {
System.out.println(e);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void writeingObject() throws IOException {
ArrayList<Person> list = new ArrayList<>();
list.add(new Person("Jason", 18));
list.add(new Person("Frank", 15));
list.add(new Person("Joker", 1));
list.add(new Person("Hanks", 35));
list.add(new Person("Tomes", 22));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\123\\person.txt"));
for (Person person : list) {
oos.writeObject(person);
}
oos.close();
}
}
打印流
package com.yu.io.print;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class Demo01PrintStream {
public static void main(String[] args) throws FileNotFoundException {
PrintStream ps = new PrintStream("D:\\123\\print.txt");
ps.write(97); //写入a
ps.println(97); //写入97 调用这个方法和输出在屏幕上一样
ps.close();
}
}
编码问题
UTF编码中每个汉字占三个字节、一个英文一个字节,适合国际化
GBK编码,每个汉字占两个字节、一个英文一个字节,适合本地化,排序更友好
new String(bytes,“编码名称”);
getBytes(“编码名称”);
在Java程序中,字符串一定是Unicode字符序列
划掉的为utf8中的标记符号