Java中的IO流(一)

Java中的IO流(一)

一、前言

学习这部分内容的时候,跟着敲代码难免有些乱,这里先放一张图:

二、实现对文件和文件夹的操作:

案例一:

package file.bytestream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileDemo1 {
    public static void main(String[] args) throws IOException {
        File f1 = new File("D:\\File\\test01.txt");
        System.out.println(f1);

        File f2 = new File("D:\\File","test02.txt");
        System.out.println(f2);

        File f3 = new File("D:\\File");
        File f4 = new File(f3,"test0.txt");

        //mkdirs()包含没有创建的文件夹也给创建处理啊
        //createNewFile()创建新文件
        System.out.println(f3.mkdirs());
        System.out.println(f4.createNewFile());

        //获取到文件的绝对路径
        System.out.println(f4.getAbsolutePath());
        //获取到文件路径
        System.out.println(f4.getPath());
        //获取到文件名字
        System.out.println(f4.getName());

        //判断f3是否为一个目录?
        if(f3.isDirectory()){
            String fileName;
            //循环创建多个文件
            for(int i = 1; i <= 40; i ++){
                fileName = "test" + i +".txt";
                new File(f3,fileName).createNewFile();
            }
            System.out.println("我要开始删除文件了!!!");
            deleteFile(f3);
        }

    }
    //删除文件
    public static void deleteFile(File f3){
        String fileName;
        for(int i = 0; i <= 40; i ++){
            System.out.println("我要开始删除test" + i + ".txt");
            fileName = "test" + i +".txt";
            new File(f3,fileName).delete();
        }
    }
}

案例二:

package file.bytestream;

import java.io.File;

public class FileDemo2 {
    public static void main(String[] args) {
        //绝对路劲与相对路劲
        //D:\\File\\a.txt   绝对路径
        //a.txt   相对路径
    }
}

二、字节流和字节缓存流:

这里提供一个快速记忆:
input 》》 输入 》》 向数组中输入 》》 从文件读取数据到数组中 》》 两种方法(一个一个、一个数组一个数组)

output 》》 输出 》》 从数组中输出 》》 从数组中输出数据到文件中 》》 write()

FileInputStream

例子一:

package file.bytestream;

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

//读取字节流
public class FileInputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        //创建字节流输入流对象
        //FileInputStream(String name)
        FileInputStream fis = new FileInputStream("myByteStream\\fos01.txt");

        int by;
        /*
         * fis.read():读数据
         * by = fis.read():把读取到的数据赋值给by
         * by != -1: 判断读取到的数据是否是-1
         * */
        while((by=fis.read())!=-1){
            System.out.print((char)by);
        }

        //释放资源
        fis.close();
    }
}

例子二:

package file.bytestream;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo02 {
    public static void main(String[] args) throws IOException {
        //创建字节流输入流对象
        FileInputStream fis = new FileInputStream("myByteStream\\fos.txt");

        byte[] bys = new byte[1024]; //1024以及整数倍
        int len;

        //循环读取
        while((len=fis.read(bys)) != -1){
            System.out.println(new String(bys,0,len));
        }

        fis.close();
    }
}

FileOutputStream

例子一:

package file.bytestream;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo01 {
    public static void main(String[] args) throws IOException {
        //创建字节输出流对象
        /*
        * 注意点:
        * 1、如果文件不存在,会帮我们创建
        *
        * 2、如果文件存在,会把文件清空
        * */
        //FileOutputStream(String name):创建文件输出流以指定的名称写入文件
        if(!new File("myByteStream").exists()){
            new File("myByteStream").mkdirs();
        }

        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
        //void write(int b): 将指定的字节写入文件输出流
        fos.write(97);
        fos.write(57);
        fos.write(55);

        //最后释放资源
        fos.close();
    }
}

例子二:

package file.bytestream;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo02 {
    public static void main(String[] args) throws IOException {
        //FileOutputStream(String name): 创建文件输出流以指定的名称写入文件
        FileOutputStream fos = new FileOutputStream("myByteStream\\fos.txt");
        byte[] bytes = "abscsd".getBytes();
        fos.write(bytes,1,3);  //从第一个索引开始,然后3个值

        //释放资源
        fos.close();
    }
}

例子三:

这个例子和trt{}catch{}结合,在finally函数内释放资源

package file.bytestream;

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

public class FileOutputStreamDemo03 {
    public static void main(String[] args) {
        //加入finally来释放资源
        FileOutputStream fos = null;
        try{
            //创建字节输出对象
             fos = new FileOutputStream("myByteStream\\fos.txt");
            InputStream(fos);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void InputStream(FileOutputStream fos) throws IOException {

        //写数据
        for(int i = 0; i < 10; i++){
            fos.write("hello".getBytes());
            fos.write("\r\n".getBytes());
        }

        //释放资源
        fos.close();
    }
}

BufferedInputStream && BufferedOutputStream

package file.bytestream;

import java.io.*;

public class BufferStreamDemo {
    public static void main(String[] args) throws IOException {
        //字节缓冲输出流: BufferedOutputStream(OutputStream out)
        BufferedOutputStream bos = new BufferedOutputStream(new
                FileOutputStream("myByteStream\\bos.txt"));

        //写数据
        bos.write("hello\r\n".getBytes());
        bos.write("world\r\n".getBytes());

        //释放资源
        bos.close();

        //字节缓冲输入流:BufferedInputStream(InputStream in)
        BufferedInputStream bis = new BufferedInputStream(new
                FileInputStream("myByteStream\\bos.txt"));

        //一次读取一个字节数据
//        int by;
//        while((by = bis.read()) != -1){
//            System.out.println((char)by);
//        }

        //一次读取一个字节数组数据
        byte[] bys = new byte[1024];
        int len;
        while((len=bis.read(bys))!=-1){
            System.out.println(new String(bys,0,len));
        }

        //释放资源
        bis.close();
    }
}

三、应用

1、使用一个一个字节进行复制:

package file.bytestream;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

//字节流复制文件

/*=============================
适合txt文件
============================*/
public class CopyFileDemo {
    public static void main(String[] args) {
        System.out.println("请按照以下一种方式书写:");
        System.out.println("1、'D:\\\\File\\\\txt01.txt'\t绝对路径");
        System.out.println("2、'File\\\\txt01.txt'\t相对路劲");
        String sourcePath = "";
        String targetPath = "";
        Scanner sc = new Scanner(System.in);
        sourcePath = sc.nextLine();
        targetPath = sc.nextLine();

//        println(sourcePath,targetPath); //验证是否有问题

        copyFileByBytes(sourcePath,targetPath);
    }

    //工具函数
    public static void copyFileByBytes(String sourcePath, String targetPath){
        FileInputStream fis = null;  //输入流,将信息输入到字节数组中并存储起来
        FileOutputStream fos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            fis = new FileInputStream(sourcePath);
            fos = new FileOutputStream(targetPath);

            //读写数据
            int by; //存储字节流(int)
            while((by = fis.read()) != -1){
                fos.write(by);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fis != null || fos != null) {
                try {
                    fis.close();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void println(String ...array){
        System.out.println(array.getClass().isArray()); //判断数据类型
        System.out.println(Arrays.toString(array));
    }
}

2、使用一个一个数组进行复制

package file.bytestream;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;

//字节流复制文件
/*=============================
适合所有文件
============================*/
public class CopyFIleDemo01 {
    public static void main(String[] args) {
        System.out.println("请按照以下一种方式书写:");
        System.out.println("1、'D:\\\\File\\\\txt01.txt'\t绝对路径");
        System.out.println("2、'File\\\\txt01.txt'\t相对路劲");
        String sourcePath = "";
        String targetPath = "";
        Scanner sc = new Scanner(System.in);
        sourcePath = sc.nextLine();
        targetPath = sc.nextLine();

//        println(sourcePath,targetPath); //验证是否有问题

        copyFileByBytes(sourcePath,targetPath);
    }

    //工具函数
    public static void copyFileByBytes(String sourcePath, String targetPath){
        FileInputStream fis = null;  //输入流,将信息输入到字节数组中并存储起来
        FileOutputStream fos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            fis = new FileInputStream(sourcePath);
            fos = new FileOutputStream(targetPath);

            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            //跟第一种使用一个一个读取字节不一样,这样做的好处是什么?
            //1、相比第一种方式使用一个字节一个字节地读取和写入,具有更高的效率。这是因为磁盘I/O操作是相对较慢的,通过一次性读取多个字节并进行批量写入,可以减少磁盘I/O操作的次数,提高数据传输的效率。
            //2、使用字节数组还可以减少内存开销,因为在Java中,一次读取多个字节并将其存储在字节数组中,可以更好地利用内存,而不是为每个字节都分配一个变量。
            byte[] bytes = new byte[1024];
            int len;
            while((len = fis.read(bytes)) != -1){
                fos.write(bytes,0,len);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(fis != null || fos != null) {
                try {
                    fis.close();
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void println(String ...array){
        System.out.println(array.getClass().isArray()); //判断数据类型
        System.out.println(Arrays.toString(array));
    }
}

3、使用BufferInputStream和BufferOutputStream以及方法一和方法二进行复制:

package file.bytestream;


import java.io.*;
import java.util.Arrays;
import java.util.Scanner;

//字节缓存流复制文件
/*=============================
适合所有文件
============================*/
public class CopyFileDemo02 {
    public static void main(String[] args) {
        System.out.println("请按照以下一种方式书写:");
        System.out.println("1、'D:\\\\File\\\\txt01.txt'\t绝对路径");
        System.out.println("2、'File\\\\txt01.txt'\t相对路劲");
        String sourcePath = "";
        String targetPath = "";
        Scanner sc = new Scanner(System.in);
        sourcePath = sc.nextLine();
        targetPath = sc.nextLine();

//        println(sourcePath,targetPath); //验证是否有问题

//        copyFileByBytes01(sourcePath,targetPath);  //字节数组读取字节流  一个数组一个数组
        copyFileByBytes02(sourcePath,targetPath); //字节流  一个一个
    }

    //工具函数
    public static void copyFileByBytes01(String sourcePath, String targetPath){
        BufferedInputStream bis = null;  //输入流,将信息输入到字节数组中并存储起来
        BufferedOutputStream bos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            bis = new BufferedInputStream(new FileInputStream(sourcePath));;
            bos = new BufferedOutputStream(new FileOutputStream(targetPath));

            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            byte[] bytes = new byte[1024];
            int len;
            while((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(bis != null || bos != null) {
                try {
                    bis.close();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void copyFileByBytes02(String sourcePath, String targetPath){
        BufferedInputStream bis = null;  //输入流,将信息输入到字节数组中并存储起来
        BufferedOutputStream bos = null; //输出流,将字节数组中的数据输出到文件中
        try{
            bis = new BufferedInputStream(new FileInputStream(sourcePath));;
            bos = new BufferedOutputStream(new FileOutputStream(targetPath));

            //读写数据,复制图片(一次读取一个字节数组,一次写入一个字节数组)
            int by; //存储字节流(int)
            while((by = bis.read()) != -1){
                bos.write(by);
            }

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(bis != null || bos != null) {
                try {
                    bis.close();
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void println(String ...array){
        System.out.println(array.getClass().isArray()); //判断数据类型
        System.out.println(Arrays.toString(array));
    }
}

posted @ 2023-11-09 20:39  news_one  阅读(11)  评论(0编辑  收藏  举报