I/O流的概念及操作

File类

    File类是java.io包中很重要的一个类,他的对象可以表示文件,还可以表示目录File对象可以对文件或目录的属性进行操作,但是无法操作文件的具体数据,即不能直接对文件进行读/写操作

 public static void main(String[] args){
        File file = new File("D:/TestDemo1.txt");
        //也可以分开标识
        //File file1 = new File("D:/","TestDemo1.txt");
        /**
         * 一些方法
         */
        System.out.println("是否是文件"+file.isFile());
        System.out.println("是否可读"+file.canRead());
        System.out.println("是否可写"+file.canWrite());
        System.out.println("是否存在"+ file.exists());
        System.out.println("绝对路径是"+file.getAbsolutePath());
        System.out.println("获取名字"+file.getName());
        System.out.println("获取上一路径"+ file.getParent());
        System.out.println("是否为隐藏文件"+ file.isHidden());
        System.out.println("创建的时间"+file.lastModified());
        //可以改为date类型
        System.out.println(new Date(file.lastModified()).toLocaleString());//转为本地区时间格式
    }
}
public static void main(String[] args) {
        /**
         * mkdir()
         * 创建由此抽象路径名命名的目录。  单文件
         * mkdirs()
         * 创建由此抽象路径名命名的目录,包括任何必需但不存在的父目录。   多级文件
         */
        File file = new File("D:/Test2");
        if(file.exists()==false){
            file.mkdir();//创建这个文件
        }
        //File file1 = new File("D:/Test3/T3");
        //file1.mkdirs();//可以创建多级对象

        /**
         * delete()
         * 删除由此抽象路径名表示的文件或目录。
         * 删除时一次只能删一级问价且文件夹为空
         * 若test2里面有文件时,无法删除
         */
        file.delete();//删掉这个文件对象,

        /**
         * list()
         * 返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录。
         * list(FilenameFilter filter)
         * 返回一个字符串数组,命名由此抽象路径名表示的目录中满足指定过滤器的文件和目录。
         */
        //获取当前目录下的所有的文件名和目录名
        File file1 = new File("D:/Test3");
        String str[] = file1.list();//list是返回字符串数组
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }

        //获取其当前目录下的所有文件对象,可以对其进行操作
        File []files = file1.listFiles();//listFiles返回的是对象
        for (int i = 0; i < files.length; i++) {
            System.out.println(files[i]);
        }
        System.out.println("----------");
        //文件过滤
        File f[] = file1.listFiles(new FileFilter() {//内部类
            @Override
            public boolean accept(File pathname) {
                return pathname.getName().endsWith("txt");//找到后缀名为txt的文件,存进f数组
            }
        });
        for (int i = 0; i < f.length; i++) {
            System.out.println(f[i]);//可对其操作
            //f[i].delete();  谨慎选择
        }
    }
}

输入及输出的概念

    输入输出(I/O):
        把电脑硬盘上的数据读到程序中,称为输入,即input,进行数据的read 操作
        从程序往外部设备写数据,称为输出,即output,进行数据的write 操作
在这里插入图片描述

字节流与字符流

从数据流编码格式上划分为
    字节流
    字符流

● 字节流中常用类
    字节输入流 FileInputStream
    字节输出流 FileOutputStream
● 字符流中常用类
    字符输入流 FileReader
    字符输出流 FileWriter

public static void main(String[] args) throws IOException {
        File file = new File("D:/Z1.txt");
        FileInputStream in = new FileInputStream(file);//可对象可字符串
        /**
         *  for (int i = 0; i < file.length(); i++) {
         *     System.out.println(in.read());//读,输入到编译器,以编码形式储存
         *  }
         */
        FileOutputStream out = new FileOutputStream("E:/Test.txt");
        for (int i = 0; i < file.length(); i++) {
            //out输出到E盘的Test文档
            out.write(in.read());//吧读到的写出去
        }
        //一定要关闭,不然可能会占用文档的使用权,导致其无法删掉
        in.close();
        out.close();
    }
}

输入流与输出流

流按着数据的传输方向分为:
    输入流:往程序中读叫输入流。
    输出流:从程序中往外写叫输出流。

● InputStream和OutputStream的子类都是字节流 可以读写二进制文件,主要处理音频、图片、歌曲、字节流,处理单元 为1个字节。
● Reader和Writer的子类都是字符流 主要处理字符或字符串,字符流处理单元为1个字符。 字节流将读取到的字节数据,去指定的编码表中获取对应文字。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 完整的Stream流输入输出
 */
public class StreamDemo2 {
    public static void main(String[] args) {
        FileInputStream in = null;
        FileOutputStream out = null;
        long a =System.currentTimeMillis();
        try {
            in = new FileInputStream("D:/001.exe");//读取进来
            out = new FileOutputStream("E:/002.exe");//写出去
            //当路径没有文件时,会自动创建一个文档
            //当读取不到字节的时候,read()会返回-1
            int n = 0;
            while((n=in.read())!=-1){
                out.write(n);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件不存在");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读取失败");
        } finally {
            try {
                if(in!=null) {
                    in.close();
                }
                if(out!=null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("关闭失败");
            }
        }
        System.out.println("一共运行了"+(System.currentTimeMillis()-a)+"毫秒");
    }
}

/**
 * 升级后的方法
 */
public class StreamDemo3 {
    public static void main(String[] args){
        FileInputStream in = null;
        FileOutputStream out = null;
        try{
            in = new FileInputStream("D:/Z1.txt");
            out = new FileOutputStream("E:/Z2.txt");

            byte[] b = new byte[100];
            int length = 0;
            while ((length=in.read(b))!=-1){
                out.write(b,0,length);
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
            System.out.println("读取失败");
        }catch (IOException io){
            io.printStackTrace();
            System.out.println("传输失败");
        }finally {
            try{
                in.close();
                out.close();
            }catch (IOException io){
                io.printStackTrace();
                System.out.println("关闭失败");
            }
        }
    }
}

节点流与处理流

节点流中常用类
    字节输入流 FileInputStream
    字节输出流 FileOutputStream
    字符输入流 FileReader
    字符输出流 FileWriter
● 处理流中常用类
    缓冲字节输出流 BufferedOutputStream
    缓冲字节输入流 BufferedInputStream
    缓冲字符输入流 BufferedReader
    缓冲字符输出流 BufferedWriter

import java.io.*;
public class BufferStreamDemo {
    public static void main(String[] args) {
        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        long a = System.currentTimeMillis();
        try {
            //低级管道,效率低
            FileInputStream in = new FileInputStream("D:/001.exe");
            FileOutputStream out = new FileOutputStream("E:/001.exe");

            //高级管道,有缓冲区 8192长度
            inputStream = new BufferedInputStream(in);//多态
            outputStream = new BufferedOutputStream(out);//多态

            byte[] b = new byte[1024];
            int length = 0;
            while((length=inputStream.read(b))!=-1){
                outputStream.write(b,0,length);
            }

            outputStream.flush();//刷新缓存区
            //此方法效率更快

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException io){
            io.printStackTrace();
        }finally {
            try {
                if(inputStream!=null) {
                    inputStream.close();
                }
                if(outputStream!=null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("一共运行了"+(System.currentTimeMillis()-a)+"毫秒");
    }
}

输入输出节点字符流

public class CharStreamDemo1 {
    /**
     *• Reader 的基本方法
     * 读取一个字符并以整数的形式返回, 如果返回-1已到输入流的末尾。
     * int read() throws IOException
     *    读取一系列字符并存储到一个数组buffer, 返回实际读取的字符数,如果读取前已到输入流的末尾返回-1
     *    int read( char[] cbuf) throws IOException关闭
     *    void close()
     *    throws IOException
     * Writer 的基本方法
     *    向输出流中写入一个字符数据,该字节数据为参数b的16位
     *    void write(int c) throws IOException 一
     *    个字符类型的数组中的数据写入输出流,
     *    void write( char[] cbuf) throws IOException
     *    将一个字符类型的数组中的从指定位置(off set)开始的 length个字符写入到输出流
     *    void write( char[] cbuf, int off set, int length) throws IOException 关闭
     *    void close() throws IOException
     */

    public static void main(String[] args) throws IOException {

        FileReader fileReader = new FileReader("E:/demo.txt");
        BufferedReader bufferedReader  = new BufferedReader(fileReader);

        FileWriter fileWriter = new FileWriter("F:/demo.txt",true);
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        String line = null; //一次读入一行数据
        while((line=bufferedReader.readLine())!=null){
            bufferedWriter.write(line);//一次写出一行数据
            bufferedWriter.newLine();//换行
        }

        bufferedReader.close();
        bufferedWriter.close();

    }
}

Print流

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Demo1 {
    /**
     * Print 打印流:只做输出没有输入 打印流分为字节打印流和字符打印流
     * PrintWriter:字符打印流 print方法可以打印各种类型数据
     */
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter printWriter = new PrintWriter("E:/001.html");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
    }
}

Print 打印流:只做输出没有输入 打印流分为字节打印流和字符打印流
PrintWriter:字符打印流 print方法可以打印各种类型数据

对象输入输出流

● 对象的输入输出流 : 主要的作用是用于写入对象信息与读取对象信息。 对象信息 一旦写到文件上那么对象的信息就可以做到持久化了
    对象的输出流: ObjectOutputStream
    对象的输入流: ObjectInputStream
● 要将序列化之后的对象保存下来,需要通过对象输出(ObjectOutputStream) 将对象状态保存,之后再通过对象输入流(ObjectInputStream)将对象状态恢复。
在ObjectInputStream 中用readObject()方法可以直接读取一个对象, ObjectOutputStream中用writeObject()方法可以直接将对象保存到输出流中。

public class Demo1 {
    /**
     * Print 打印流:只做输出没有输入 打印流分为字节打印流和字符打印流
     * PrintWriter:字符打印流 print方法可以打印各种类型数据
     */
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter printWriter = new PrintWriter("E:/001.html");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
        printWriter.println("<h1>这是一段信息</h1>");
    }
}

/**
     * 对象输出流
     * 对象的输入输出流 : 主要的作用是用于写入对象信息与读取对象信息。
     * 对象信息 一旦写到文件上那么对象的信息就可以做到持久化了
     *
     * 对象的输出流:
     *     ObjectOutputStream
     * 对象的输入流:
     *     ObjectInputStream
     */
    public static void main(String[] args) throws IOException {
        Date date = new Date();
        //对象输出流
        FileOutputStream out = new FileOutputStream("E:/001.txt");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(out);
        objectOutputStream.writeObject(date);
    }
}

public class Demo2 {
    /**
     * 对象输入流
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        FileInputStream in = new FileInputStream("E:/001.txt");
        ObjectInputStream objectInputStream = new ObjectInputStream(in);
        Object obj  = objectInputStream.readObject();//将对象信息从文件中传输到程序中 是对象的反序列化
        Date date = (Date)obj;
        System.out.println(date);
    }
}

对象序列化

public class Demo3 implements Serializable {//在需要储存对象的类使用
    /**
     * 如果需要将一个类的对象信息序列化到文件中,
     *
     *  implement Serializable默认会在出类生成一个版本号
     *  但是一旦类的信息发生改变,版本号会自动改变
     *     也可以先生生成版本号,类的发生修改是,版本号不会改变
     */
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("");
        ObjectInputStream objectInputStream = new ObjectInputStream(in);
          // Student student = new (Student)objectInputStream.readObject();
        /**
         * 对象的输出流将指定的对象写入到文件的过程,就是将对象序列化的过程
         * 对象的输入流将指定序列化好的文件读出来的过程,就是对象反序列化的过程。
         *
         * 既然 对象的输出流将对象写入到文件中称之为对象的序列化,所以必须要实现 Serializable接口。
         * Serializable接口中没有任何方法。当一个类声明实现Serializable接口后, 表明该类可被序列化。
         *     在类中可以生成一个编号
         *     private static final long serialVersionUID = -5974713180104013488L;
         * 随机生成 唯一的 serialVersionUID 用来表明实现序列化类的不同版本间的兼容性。
         * 某个类在 与之对应的对象已经序列化出去后做了修改,该对象依然可以被正确反序列化
         */

    }
}

● 对象的寿命通常随着生成该对象的程序的终止而终止。 有时候,可能需要将对象的状态保存下来,在需要时再将对象恢复
● 对象的输出流将指定的对象写入到文件的过程,就是将对象序列化的过程,对象 的输入流将指定序列化好的文件读出来的过程,就是对象反序列化的过程。既然 对象的输出流将对象写入到文件中称之为对象的序列化,所以必须要实现 Serializable接口

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这个实验的主要目的是让学生掌握Java中文件及目录操作的基本概念和使用方法,同时能够处理异常情况,确保程序的健壮性。下面我将为你详细介绍实现步骤。 1. 文件与目录的创建 使用Java中的File类可以很方便地对文件和目录进行创建,示例代码如下: ```java // 创建文件 File file = new File("test.txt"); if (file.createNewFile()) { System.out.println("文件创建成功!"); } else { System.out.println("文件已存在!"); } // 创建目录 File dir = new File("testDir"); if (dir.mkdir()) { System.out.println("目录创建成功!"); } else { System.out.println("目录已存在!"); } ``` 2. 文件的读写 使用Java中的输入输出可以很方便地对文件进行读写操作,示例代码如下: ```java // 写入文件 try (FileWriter writer = new FileWriter("test.txt")) { writer.write("Hello, world!"); writer.flush(); System.out.println("写入成功!"); } catch (IOException e) { e.printStackTrace(); } // 读取文件 try (FileReader reader = new FileReader("test.txt")) { int c; while ((c = reader.read()) != -1) { System.out.print((char) c); } } catch (IOException e) { e.printStackTrace(); } ``` 3. 文件的复制 使用Java中的输入输出和缓冲区可以很方便地对文件进行复制操作,示例代码如下: ```java // 复制文件 try (FileInputStream input = new FileInputStream("test.txt"); FileOutputStream output = new FileOutputStream("test_copy.txt")) { byte[] buffer = new byte[1024]; int len; while ((len = input.read(buffer)) != -1) { output.write(buffer, 0, len); } System.out.println("复制成功!"); } catch (IOException e) { e.printStackTrace(); } ``` 4. 异常处理 在对文件进行操作时,可能会遇到一些异常情况,例如文件不存在、无法读取等,我们需要对这些异常进行处理,以保证程序的健壮性。示例代码如下: ```java // 读取不存在的文件 try (FileReader reader = new FileReader("notExist.txt")) { int c; while ((c = reader.read()) != -1) { System.out.print((char) c); } } catch (IOException e) { System.out.println("文件不存在!"); } ``` 以上就是实现文件与目录的创建、读写、复制等基本操作以及对异常情况进行处理的方法。希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值