21 文件与IO

lix_uan
• 阅读 929

java.io.File类

构造方法

// 文件路径名
String pathname = "D:\\aaa.txt";
File file1 = new File(pathname); 

// 文件路径名
String pathname2 = "D:\\aaa\\bbb.txt";
File file2 = new File(pathname2); 

// 通过父路径和子路径字符串
 String parent = "d:\\aaa";
 String child = "bbb.txt";
 File file3 = new File(parent, child);

// 通过父级File对象和子路径字符串
File parentDir = new File("d:\\aaa");
String child = "bbb.txt";
File file4 = new File(parentDir, child);

获取文件和目录信息

  • public String getName() :返回由此File表示的文件或目录的名称
  • public long length() :返回由此File表示的文件的长度

获取路径

  • public String getPath() :将此File转换为路径名字符串
  • public String getParent() :获得父级路径
  • public String getAbsolutePath() :返回此File的绝对路径名字符串

判断

  • public boolean exists() :此File表示的文件或目录是否实际存在
  • public boolean isDirectory() :此File表示的是否为目录
  • public boolean isFile() :此File表示的是否为文件

创建删除

  • public boolean createNewFile() :当且仅当具有该名称的文件尚不存在时,创建一个新的空文件
  • public boolean delete() :删除由此File表示的文件或目录。 只能删除空目录
  • public boolean mkdirs() :创建由此File表示的目录,包括任何必需但不存在的父目录

目录的遍历

  • public String[] list() :返回一个String数组,表示该File目录中的所有子文件或目录
  • public File[] listFiles() :返回一个File数组,表示该File目录中的所有的子文件或目录

递归删除非空目录

@Test
public void test6() {
    File dir = new File("D:/atguigu/javase");
    forceDeleteDir(dir);
}
public void forceDeleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        File[] listFiles = dir.listFiles();
        if(listFiles!=null){
            for (File sub : listFiles) {
                forceDeleteDir(sub);
            }
        }
    }
    dir.delete();
}

字节流

字节输出流

常用API

  • public void close() :关闭此输出流并释放与此流相关联的任何系统资源

  • public void flush() :刷新此输出流并强制任何缓冲的输出字节被写出

  • public void write(byte[] b):将 b.length字节从指定的字节数组写入此输出流

  • public void write(byte[] b, int off, int len) :从指定的字节数组写入 len字节,从偏移量 off开始输出到此输出流

  • public FileOutputStream(File file, boolean append): 创建文件输出流以写入由指定的 File对象表示的文件

  • public FileOutputStream(String name, boolean append): 创建文件输出流以指定的名称写入文件

    public class FOSWrite {
        public static void main(String[] args) throws IOException {
            // 使用文件名称创建流对象
            FileOutputStream fos = new FileOutputStream("fos.txt",true);     
              // 字符串转换为字节数组
              byte[] b = "abcde".getBytes();
            // 写出从索引2开始,2个字节。索引2是c,两个字节,也就是cd。
            fos.write(b);
              // 关闭资源
            fos.close();
        }
    }
    文件操作前:cd
    文件操作后:cdabcde

写出换行

  • Windows系统里,每行结尾是 回车+换行 ,即\r\n
  • Unix系统里,每行结尾只有 换行 ,即\n
  • Mac系统里,每行结尾是 回车 ,即\r。从 Mac OS X开始与Linux统一

字节输入流

常用API

  • public void close() :关闭此输入流并释放与此流相关联的任何系统资源。
  • public abstract int read(): 从输入流读取数据的下一个字节。
  • public int read(byte[] b): 从输入流中读取一些字节数,并将它们存储到字节数组 b中

使用字节数组读取

public class FISRead {
    public static void main(String[] args) throws IOException{
          // 使用文件名称创建流对象.
           FileInputStream fis = new FileInputStream("read.txt"); // 文件中为abcde
          // 定义变量,作为有效个数
        int len ;
        // 定义字节数组,作为装字节数据的容器   
        byte[] b = new byte[2];
        // 循环读取
        while (( len= fis.read(b))!=-1) {
               // 每次读取后,把数组的有效字节部分,变成字符串打印
            System.out.println(new String(b,0,len));//  len 每次读取的有效字节个数
        }
        // 关闭资源
        fis.close();
    }
}

输出结果:
ab
cd
e

字符流

字符输入流

使用字符数组读取

public class FISRead {
    public static void main(String[] args) throws IOException {
          // 使用文件名称创建流对象
           FileReader fr = new FileReader("read.txt");
          // 定义变量,保存有效字符个数
        int len ;
        // 定义字符数组,作为装字符数据的容器
        char[] cbuf = new char[2];
        // 循环读取
        while ((len = fr.read(cbuf))!=-1) {
            System.out.println(new String(cbuf,0,len));
        }
        // 关闭资源
        fr.close();
    }
}

字符输出流

关闭和刷新

  • flush:刷新缓冲区,流对象可以继续使用
  • close:刷新缓冲区,然后通知系统释放资源,流对象不可以再被使用了

写出字符数组

public class FWWrite {
    public static void main(String[] args) throws IOException {
        // 使用文件名称创建流对象
        FileWriter fw = new FileWriter("fw.txt");     
          // 字符串转换为字节数组
          char[] chars = "博客园".toCharArray();

          // 写出字符数组
          fw.write(chars); // 博客园

        // 写出从索引1开始,2个字节。索引1是'博',两个字节,也就是'博客'。
        fw.write(b,1,2); // 博客

          // 关闭资源
        fos.close();
    }
}

字节缓冲流

// 创建字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("bis.txt"));
// 创建字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bos.txt"));

字符缓冲流

// 创建字符缓冲输入流
BufferedReader br = new BufferedReader(new FileReader("br.txt"));
// 创建字符缓冲输出流
BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

特有方法

  • BufferedReader:public String readLine(): 读一行文字。
  • BufferedWriter:public void newLine(): 写一行行分隔符,由系统属性定义符号。

转换流

指定编码读取

public class ReaderDemo2 {
    public static void main(String[] args) throws IOException {
          // 定义文件路径,文件为gbk编码
        String FileName = "E:\\file_gbk.txt";
          // 创建流对象,默认UTF8编码
        InputStreamReader isr = new InputStreamReader(new FileInputStream(FileName));
          // 创建流对象,指定GBK编码
        InputStreamReader isr2 = new InputStreamReader(new FileInputStream(FileName) , "GBK");
        // 定义变量,保存字符
        int read;
          // 使用默认编码字符流读取,乱码
        while ((read = isr.read()) != -1) {
            System.out.print((char)read); // ��Һ�
        }
        isr.close();

          // 使用指定编码字符流读取,正常解析
        while ((read = isr2.read()) != -1) {
            System.out.print((char)read);// 大家好
        }
        isr2.close();
    }
}

转换流图解

21 文件与IO

序列化

概述

  • Java提供了一种对象序列化机制,用一个字节序列可以表示一个对象
  • 该字节序列包含该对象的类型和对象中存储的属性等信息
  • 字节序列写出文件后,相当于文件中持久保存了一个对象的信息

序列化图解

21 文件与IO

序列化操作

  • 该类必须实现Serializable接口

  • 如果某个属性不需要被序列化,则要用transient关键字修饰

    public class Employee implements java.io.Serializable {
        public static String company = "博客园";
        public String name;
        public String address;
        public transient int age; // transient瞬态修饰成员,不会被序列化
        public void addressCheck() {
              System.out.println("Address  check : " + name + " -- " + address);
        }
    }

写出对象

public class SerializeDemo{
       public static void main(String [] args)   {
        Employee e = new Employee();
        e.name = "zhangsan";
        e.address = "beiqinglu";
        e.age = 20; 
        try {
              // 创建序列化流对象
          ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"));
            // 写出对象
            out.writeObject(e);
            // 释放资源
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved"); // 姓名,地址被序列化,年龄没有被序列化。
        } catch(IOException i)   {
            i.printStackTrace();
        }
       }
}
输出结果:
Serialized data is saved

读取对象

public class DeserializeDemo {
   public static void main(String [] args)   {
        Employee e = null;
        try {        
             // 创建反序列化流
             FileInputStream fileIn = new FileInputStream("employee.txt");
             ObjectInputStream in = new ObjectInputStream(fileIn);
             // 读取一个对象
             e = (Employee) in.readObject();
             // 释放资源
             in.close();
             fileIn.close();
        }catch(IOException i) {
             // 捕获其他异常
             i.printStackTrace();
             return;
        }catch(ClassNotFoundException c)  {
            // 捕获类找不到异常
             System.out.println("Employee class not found");
             c.printStackTrace();
             return;
        }
        // 无异常,直接打印输出
        System.out.println("Name: " + e.name);    // zhangsan
        System.out.println("Address: " + e.address); // beiqinglu
        System.out.println("age: " + e.age); // 0
    }
}

JDK1.7之后引入新try...catch

语法格式

try(需要关闭的资源对象的声明){
    业务逻辑代码
}catch(异常类型 e){
    处理异常代码
}catch(异常类型 e){
    处理异常代码
}
....
//没有finally,也不需要生许愿手动关闭资源对象
//无论是否发生异常,都会关闭资源对象

示例

@Test
public void test03() {
    //从d:/1.txt(GBK)文件中,读取内容,写到项目根目录下1.txt(UTF-8)文件中
    try(
        FileInputStream fis = new FileInputStream("d:/1.txt");
        InputStreamReader isr = new InputStreamReader(fis,"GBK");
        BufferedReader br = new BufferedReader(isr);

        FileOutputStream fos = new FileOutputStream("1.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF-8");
        BufferedWriter bw = new BufferedWriter(osw);
    ){
        String str;
        while((str = br.readLine()) != null){
            bw.write(str);
            bw.newLine();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
点赞
收藏
评论区
推荐文章

暂无数据

lix_uan
lix_uan
Lv1
学无止境,即刻前行
文章
7
粉丝
5
获赞
0