File,IO流与IO流异常处理

File

File类用于封装一个文件路径,可以描述一个文件或文件夹,通过File对象可以读取文件或者文件夹的属性数据,但是读取文件的内容,就需要使用IO流技术。

构造函数
 public static void demo() {
        File file = new File("E:/Demo");
        File file1 = new File("E:", "Demo1");
        File file2 = new File(file, "Test");
}
创建
public static void demo() throws IOException {
        String filePath = "E:/Demo/Test";
        File file = new File(filePath);
        file.mkdir();//创建单级文件夹,"E:/Demo"
        file.mkdirs(); //创建多级文件夹,"E:/Demo/Test"
        file.createNewFile();//创建文件,"E:/Demo/Test.txt"
}
删除
public static void demo() {
        String filePath = "E:/Demo";
        File file = new File(filePath);
        file.delete();
        file.deleteOnExit();
}
重命名
 public static void demo() {
        File file1 = new File("E:", "Demo");
        file1.mkdir();

        File file2 = new File("E:", "Changed");
        file1.renameTo(file2); //重命名
    }
判断
 public static void demo() {
        File file = new File("E:", "Demo");
        boolean exists = file.exists(); //判断文件是否存在
        boolean directory = file.isDirectory(); //判断是否为文件夹
        boolean file1 = file.isFile();//判断是否为文件
        boolean hidden = file.isHidden();//判断文件是否隐藏
        boolean absolute = file.isAbsolute();//判断是否为绝对路径
}
获取
 public static void demo() {
        File file = new File("E:", "Demo");
        file.mkdir();

        String name = file.getName();
        String path = file.getPath();
        String absolutePath = file.getAbsolutePath();
        String parent = file.getParent();
        long length = file.length();

        long lastModified = file.lastModified();
        Date date = new Date(lastModified);
        SimpleDateFormat format = new SimpleDateFormat("yyyy年HH月dd日 hh:MM:ss");
        System.out.println(format.format(date));
    }
文件夹相关
 public static void demo() {
        File file = new File("E:", "Demo");
        file.mkdir();

        String[] list = file.list();//获取当前文件夹下的所有子文件与子文件夹名
        File[] files = file.listFiles();//获取当前文件夹下的所有子文件与子文件夹
}

IO流

OutputStream(字节输出流)
FileOutputStream(字节输出流)

public static void write(File file) {

        try (
                //如果目标文件不存在,会自动创建目标文件对象
                //如果目标文件已经存在,会先清空目标文件中的数据然后再写入数据
                //FileOutputStream fos = new FileOutputStream(file)

                //如果目标文件已存在,想要追加数据,使用此构造方法
                FileOutputStream fos = new FileOutputStream(file, true)
        ) {
            String str = "Demo write data";

            //虽然接收的是一个int类型的数据,但是真正写出的只是一个字节的数据
            //只是把低八位的二进制数据写出,其他二十四位数据全部丢弃
            fos.write(str.getBytes());
            fos.flush();
            System.out.println("写入成功");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedOutputStream(缓冲字节输出流)

 public static void write(File file) {
        try (
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
        ) {

            String str = "Demo write data";

            //先把数据写到它内部维护的字节数组中
            bos.write(str.getBytes());
            //如果真正写到硬盘上就需要调用它的flush,或close方法
            // 或者内部维护的字节数据已经填满数据的时候也会刷出去
            bos.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
InputStream(字节输入流)
FileInputStream(字节输入流)

public static void read(File file) {
        try (
                FileInputStream fis = new FileInputStream(file)
        ) {
            //用于声明文件读取到那里
            int len;

            // 建立缓冲字节数组,大小一般用1024倍数,理论上越高效率越高
            byte bur[] = new byte[1024];

            // 如果使用read传入字节数组,那么数据是存储到字节数组的,
            // 返回值是存储到缓冲数组中字节个数,-1为结束
            while ((len = fis.read(bur)) != -1) {
                System.out.println(new String(bur, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedInputStream(缓冲字节输入流)

public static void read(File file) {

        try (
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis)
        ) {

            int len;

            // BufferedInputStream本身是不具备读写文件能力
            // 需要借助FileInputStream来读取文件的数据
            while ((len = bis.read()) != -1) {
                System.out.println((char) len);
            }

            // 关闭调用BufferedInputStream.close()实际是调用FileInputStream.close()
            bis.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Writer(字符输出流)
FileWriter(字符输出流)

 public static void write(File file) {
        try (
                FileWriter writer = new FileWriter(file, true)
        ) {
            String str = "Demo write data";

            // 内部维护了一个1024个字符数组的,写数据的时候会先写入它内部维护的字符数组中,
            // 如果需要把数据真正写到硬盘,需要调用flush或者close或者是填满内存的字符数组。
            writer.write(str);
            writer.flush();
            System.out.println("写入成功");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedWriter(缓冲字符输出流)
public static void write(File file) {
        try (
                FileWriter writer = new FileWriter(file, true);
                BufferedWriter bw = new BufferedWriter(writer);
        ) {
            String str = "Demo write data";

            bw.write(str);
            bw.flush();
            bw.close();
            System.out.println("写入成功");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Reader(字符输入流)

FileReader(字符输入流)

public static void read(File file) {
        try (
                FileReader reader = new FileReader(file);
        ) {

            int len;
            char buf[] = new char[1024];
            while ((len = reader.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
BufferedReader(缓冲字符输入流)

 public static void read(File file) {
        try (
                FileReader reader = new FileReader(file);
                BufferedReader br = new BufferedReader(reader);
        ) {

            String len = null;
            while ((len = br.readLine()) != null) {
                System.out.println(len);
                br.lines();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

InputStreamReader,OutputStreamWriter(转换流)

将字节流转换为字符流

 public static void demo(File file) {
        try (
                FileOutputStream fos = new FileOutputStream(file, true);
                FileInputStream fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos))
        ) {
            String str = "Demo write data";
            bw.write(str);
            bw.flush();

            String len;
            while ((len = br.readLine()) != null) {
                System.out.println(len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

SequenceInputStream(合并流)

 public static void split() {
        //目标文件
        File goalFile = new File("E:", "Demo/Demo.mp3");
        //结果文件
        File resultFile = new File("E:", "Demo/Split");

        try (
                FileInputStream fis = new FileInputStream(goalFile);
        ) {
            int len;
            byte bur[] = new byte[1024 * 1024];

            for (int i = 1; (len = fis.read(bur)) != -1; i++) {
                FileOutputStream fos = new FileOutputStream(
                        new File(resultFile, "split" + i + ".mp3"));
                fos.write(bur, 0, len);
                fos.flush();
                fos.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

   public static void merge() {
        //碎片所在文件夹
        File goalFile = new File("E:", "Demo/Split");
        File[] files = goalFile.listFiles(); //获取文件下所有文件

        Vector<FileInputStream> vector = new Vector<>();
        for (File item : files) {
            //判断是否为MP3格式
            if (item.getName().endsWith(".mp3")) {
                try {
                    vector.add(new FileInputStream(item));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        Enumeration<FileInputStream> elements = vector.elements();
        SequenceInputStream sis = new SequenceInputStream(elements);
        File resultFile = new File("E:", "merge.mp3");

        try (
                FileOutputStream fileOutputStream = new FileOutputStream(resultFile);
        ) {
            byte buf[] = new byte[1024];
            int len;

            while ((len = sis.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, len);
            }
            fileOutputStream.flush();
            sis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PrintStream(打印流),DataOutputStream(数据流)

PrintStream(打印流)
  • 可以打印任何类型的数据,而且打印数据之前都会先把数据转换成字符串,再进行打印的。
  • 收集异常的日志信息。
 public static void demo() throws FileNotFoundException {
        try (PrintStream printStream = new PrintStream(
                new File("E:", "Demo.txt"))) {

            printStream.println();//通过此函数打印任何数据

        } catch (FileNotFoundException e) {
            PrintStream printStream = new PrintStream(
                    new File("E:", "Demo.txt"));
            e.printStackTrace(printStream); //打印到指定文本
        }
    }
DataOutputStream(数据流)
public static void demo() throws IOException {
        File file = new File("E:/Demo.txt");

        //写入
        DataOutputStream dos = new DataOutputStream(
                new FileOutputStream(file));
        dos.writeUTF("通过Write方法,写入任何数据");

        //读取
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        String readUTF = dis.readUTF();
        System.out.println("需要对应读取" + readUTF);
    }

内存流

所谓内存流,是将信息暂时存储在内存中。
内存流本身就是内存中的资源,流中的内容也是内存中的资源,理论上是不用关闭流,内存也会将其释放,但是最好还是手动关一下。

public static void demo() throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write("Demo".getBytes());

        //从内存中拿出
        byte[] buf = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(buf);
        int len;
        byte resBuf[] = new byte[1024];
        while ((len = bais.read(resBuf)) != -1) {
            System.out.println(new String(resBuf, 0, len));
        }
        bais.close();
    }

PipedInputStream(管道流)

管道流用于线程间的通信

PipedInputStream
PipedOutputStream
PipedReader
PipedWriter
//A线程发送数据给B线程
class AThread extends Thread {

    PipedOutputStream pipedOutput = new PipedOutputStream();

    public PipedOutputStream getPipedOutput() {
        return pipedOutput;
    }

    @Override
    public void run() {

        try {

            for (int i = 65; i < 65 + 26; i++) {
                pipedOutput.write(i);
            }

            pipedOutput.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//B线程接收A发送的数据
class BThread extends Thread {

    PipedInputStream pipedInput;

    //需要将管道流连接才能通信,由此piped的流构造方法允许传入对应管道流
    public BThread(AThread aThread) throws IOException {
        pipedInput = new PipedInputStream(aThread.getPipedOutput());
    }

    @Override
    public void run() {
        int len = 0;
        try {
            while ((len = pipedInput.read()) != -1) {
                System.out.println((char) len);
            }
            pipedInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

IO异常处理
传统方式处理IO异常
public class Run {
    public static void main(String[] args) {

        copy();
    }

    public static void copy() {

        // 目标拷贝文件路径

        File file = new File("D:" + File.separator + "Test.txt");
        // 存放路径
        File file2 = new File("E:" + File.separator + "Test.txt");
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            fileOutputStream = new FileOutputStream(file2);
            int len = 0;
            byte[] bur = new byte[1024];

            while ((len = fileInputStream.read(bur)) != -1) {
                fileOutputStream.write(bur, 0, len);
            }

        } catch (IOException e) {

            // 首先终止代码,然后通知调用者出现问题
            // 把IOException传递给RuntimeException包装一层,让调用者使用更加灵活
            System.out.println("读取资源出错");
            throw new RuntimeException(e);

        } finally {
            try {

                // 关闭资源原则
                // 先开后关
                // 后开先关

                if (fileOutputStream != null) {
                    fileOutputStream.close();
                    System.out.println("关闭输出流资源成功");
                }

            } catch (IOException e) {
                System.out.println("关闭输出流资源出错");
                throw new RuntimeException(e);
            } finally {
                try {
                    if (fileInputStream != null) {
                        fileInputStream.close();
                        System.out.println("关闭输入流资源成功");
                    }
                } catch (IOException e) {
                    System.out.println("关闭输入流资源出错");
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
AutoCloseable处理IO异常

JDK1.7提供了AutoCloseable接口来自动关闭资源,从源码体系上看InputStream实现了Closeable接口,而Closeable接口为AutoCloseable的子类。

public static void demo(){
        try(
                //打开资源代码
            
            ){
            
            //可能出现异常的代码
            //读写操作
            
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static void demo() {
        File file = new File("D:" + File.separator + "Test.txt");
        try (
                
                FileInputStream fileInputStream = new FileInputStream(file);
            
            ) {

            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(buf)) != -1) {
                System.out.println(new String(buf, 0, len));
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • 1 IONo18 1.1IO框架 【 IO:Input Output 在程序运行的过程中,可能需要对一些设备进...
    征程_Journey阅读 978评论 0 1
  • IO流(Input Output) IO技术主要的作用是解决设备与设备之间 的数据传输问题。硬盘 -> 内存内存的...
    奋斗的老王阅读 4,309评论 1 48
  • 第十七天进程和线程-------- 1.进程: 就是正在运行的程序,分配内存让应用程序能够运行。 Windows系...
    枇杷树8824阅读 1,017评论 0 0
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,239评论 2 33