文章目录
一、文件和目录
File类:文件和目录的封装。
1、文件
public static void main(String[] args) throws IOException {
// File f = new File("f:\\data\\a.txt");
// File f = new File("f:/data/a.txt");// (1)
// File f = new File("f:/data/","a.txt"); //(2) 父路径,文件
File ff = new File("f:/data/");
File f = new File(ff,"a.txt");// (3)
// 1. 文件和目录是否存在,存在 true
System.out.println(f.exists());// false
// 2. 新建文件
f.createNewFile();
// 3. 获得文件所在的路径
System.out.println(f.getPath());// f:\data\a.txt
// 4. 可以读,true
System.out.println(f.canRead());// true
// 5 可以写(修改) true
System.out.println(f.canWrite());// true
// 6. 是否是问文件,是 true
System.out.println(f.isFile());//true
// 7. 最后修改的时间
long date = f.lastModified();
// 1)
Date date1 = new Date(date);
System.out.println(date1);
// 2)
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
System.out.println(df.format(date));
// 8. 文件的长度 long
System.out.println(f.length());// 0
// 9. 删除
f.delete();
System.out.println(f.exists());
}
2.目录
目录方法一:
File f = new File("f:/data");
// 1.
System.out.println(f.exists());// true
// 2. 是否是目录
System.out.println(f.isDirectory());
//
File ff = new File("f:/data2/data3");
// 3.新建目录 父目录不存在不会创建的
// ff.mkdir();
// 4.新建目录 父目录不存在会创建的
ff.mkdirs();
函数式接口:
1. FilenameFileter:文件名过滤器
@FunctionalInterface
public interface FilenameFilter {
// 父路径, 文件名
boolean accept(File dir, String name);
}
2.Filefilter:文件过滤器
@FunctionalInterface
public interface FileFilter {
boolean accept(File pathname);
}
目录方法二:
public static void main(String[] args) {
File f = new File("f:/data");
//------------------------list()----------------------------
// 1.list() 获得目录下的文件和子目录的字符串数组
String [] fs = f.list();
// Arrays.stream(fs).forEach(System.out::println);
// 2. 筛选 java文件
fs = f.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith("java");
}
});
fs = f.list((dir,name)->name.endsWith("jpg"));
Arrays.stream(fs).forEach(System.out::println);
//------------------------------------------------------
System.out.println("--------------------------------");
// 获得 目录下的子目录和文件的File 数组
File [] fes = f.listFiles();
/* for(File fi : fes) {
if(fi.isFile()) {
System.out.println("文件:" + fi.getName());
}else if(fi.isDirectory()) {
System.out.println("目录:" + fi.getPath());
}
}*/
// 过滤 java文件
fes = f.listFiles(new FileFilter() {
@Override //
public boolean accept(File pathname) {
return pathname.getName().endsWith("java");
}
});
fes = f.listFiles(p->p.getName().endsWith("class"));
for(File fi : fes) {
if(fi.isFile()) {
System.out.println("文件:" + fi.getName());
}else if(fi.isDirectory()) {
System.out.println("目录:" + fi.getPath());
}
}
}
二、流
1.分类
1)按照流的数据类型:分为字节流和字符流
2)按照方向:输入和输出
3)按照功能:节点流和处理流
节点流:直接对数据源进行操作的流。
处理流:过滤流,包装类。 包装在节点流上的。
2.字节流
2.1 文件流
节点流:FileInputStream
FileOutputStream
基本的读:
public static void main(String[] args) throws IOException {
// 读:把 f:/data/a.txt 文件内容读出来,在控制台上展示
// 1. 创建流对象
// 引发: FileNotFoundException
FileInputStream fin = new FileInputStream("f:/data/a.txt");
// File f = new File("f:/data/a.txt");
// FileInputStream fin = new FileInputStream(f);
// 2. 读 read() 读取下一字节
// 引发: IOException
/* System.out.println((char)fin.read());
System.out.println((char)fin.read());
System.out.println((char)fin.read());
System.out.println(fin.read());// -1 文件尾
*/ // 循环读
int temp;
while((temp = fin.read())!= -1) {
System.out.print((char)temp);
}
// 3.关闭流
fin.close();
}
2.2 转换字符流
InputStreamReader
OutputStreamWriter
public static void main(String[] args) throws IOException {
// 读:把 f:/data/a.txt 文件内容读出来,在控制台上展示
// 1. 创建流对象 字节流
FileInputStream fin = new FileInputStream("f:/data/a.txt");
// 把 字节流 -》 转换成 字符流 转换字符流
InputStreamReader ir = new InputStreamReader(fin);
// 2. 读 read() 读取下一字节
// 中文问题:
// (1) 字符流处理:一次读一个字符
int temp;
while((temp = ir.read())!= -1) {
System.out.print((char)temp);
}
// 3.关闭流
// fin.close();
// ir.close();
ir.close();
}
中文处理方式二:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// 读:把 f:/data/a.txt 文件内容读出来,在控制台上展示
// 1. 创建流对象 字节流
// File f = new File("f:/data/a.txt");
// FileInputStream fin = new FileInputStream(f);
FileInputStream fin = new FileInputStream("f:/data/a.txt");
// 2. 读 read() 读取下一字节
// 中文问题:
// (2) 读完之后,统一展示
// byte [] b = new byte[(int)f.length()];// (1)获得文件内容的字节数
byte [] b = new byte[fin.available()];// (2)获得文件内容的字节数
fin.read(b);
// 把字节数组转换成字符串String
String str = new String(b, "GBK");
System.out.println(str);
// 3.关闭流
fin.close();
}
输出:
public static void main(String[] args) throws IOException {
// String s = "hello"; 存到 b.txt
// 1. 对象 FileNotFoundException
// false (默认) 覆盖 ,true 追加
FileOutputStream fout = new FileOutputStream("f:/data/b.txt",true);
// 2.写 IOException
// 1) 一次写一个字节
/* String s = "hello你好";
int len = s.length();
int i = 1;
while(i <= len) {
fout.write(s.charAt(i-1));
i ++;
}*/
// 2) 中文
String s = "hello";
byte [] b = s.getBytes();
fout.write(b);
// 3. 关
fout.close();
}
异常处理方式:
public class TestFileOutputStream2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileOutputStream fout = null; // 空对象
try {
fout = new FileOutputStream("f:/data/b.txt");
// 2.
fout.write("hello".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 3.
try {
if(fout != null)
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.3 缓冲流
BufferedInputStream
BufferdOutputStream
public static void main(String[] args) throws IOException {
// 1.
FileInputStream fin = new FileInputStream("f:/data/aoteman.jpg");
BufferedInputStream bfin = new BufferedInputStream(fin);
FileOutputStream fout = new FileOutputStream("f:/data/aotemannew.jpg");
BufferedOutputStream bfout = new BufferedOutputStream(fout);
// 2.
int temp;
while((temp = bfin.read())!= -1) {
bfout.write(temp);
}
//
bfout.flush();// 强制刷新缓冲区
// 3.
fin.close();
fout.close();
}
2.4 对象流
ObjectInputStream : 读,输入, 把磁盘文件中的对象还原。 反序列化。
ObjectOutputStream : 写,输出,把对象 写入到磁盘文件。 序列化
class Student implements Serializable{
/**
* 序列化与反序列化的版本号一致。
*/
private static final long serialVersionUID = 1L;
private int no;
private String name;
private int age;
public Student(int no, String name) {
super();
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "Student [no=" + no + ", name=" + name + "]";
}
}
public class TestObjectInputStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
/*// 序列化: 把 guojing 存到 obj.txt
Student guojing = new Student(11, "郭靖");
// 1.
FileOutputStream fout = new FileOutputStream("f:/data/obj.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fout);
//2.
objOut.writeObject(guojing);// 写
// 3.
objOut.close();*/
//------------------反序列化---------------------------------------
// 把obj.txt中的对象 还原
// 1.
FileInputStream fin = new FileInputStream("f:/data/obj.txt");
ObjectInputStream objFin = new ObjectInputStream(fin);
// 2.
Student stu = (Student)objFin.readObject();
System.out.println(stu.toString());
// 3.
objFin.close();
}
}
3.字符流
处理文本文件。
3.1 文件流
节点流。
FileReader
FileWriter
读:
public static void main(String[] args) throws IOException {
// a.txt
// 1.
FileReader fr = new FileReader("f:/data/a.txt");
// 2. 一次读下一个字符
// System.out.println((char)fr.read());
// 1) 循环
/* int temp ;
while((temp = fr.read()) != -1) {
System.out.print((char)temp);
}*/
// 2)
char [] cs = new char[6];
fr.read(cs);
System.out.println(new String(cs));
// 3.
fr.close();
}
写:
public static void main(String[] args) throws IOException {
// Sting str = "hello你好" b.txt
// 1. true追加 ,false 默认 覆盖
FileWriter fw = new FileWriter("f:/data/b.txt",true);
// 2.
String str = "tom";
fw.write(str);
// 3.
fw.close();
}
3.2 缓冲流
BufferedReader
BufferedWriter
public static void main(String[] args) throws IOException {
// 1
FileReader fr = new FileReader("f:/data/Demo4.java");
BufferedReader bfr = new BufferedReader(fr);
// 2
/* int temp ;
// 一次读一个字符
while((temp = fr.read()) != -1) {
System.out.print((char)temp);
}*/
// 一次读一行
// System.out.println(bfr.readLine());
// System.out.println(bfr.readLine());// null 文件尾
// 循环
String s ;
while((s = bfr.readLine()) != null) {
System.out.println(s);
}
// 3.
fr.close();
}
3.3 文本输出流
PrintWriter
public static void main(String[] args) throws IOException {
// 把 控制台上内容 写入 文件 number.txt
// 1.
PrintWriter pw = new PrintWriter("f:/data/number.txt");
// 2.
for(int i = 1; i <= 5 ; i ++) {
pw.println("数字是:" + i);
}
// 3.
pw.close();
}
三.try-with-resources 自动资源释放
只要实现了 AutoCloseable 接口,就可以自动资源释放
try (PrintWriter pw = new PrintWriter("f:/data/number.txt");){
// 2.
for(int i = 1; i <= 5 ; i ++) {
pw.println("数字是:" + i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}