Java文件操作

文件操作


JDK中对文件操作的有关类都在java.io包中

对文件操作可以使用File类

File类

//使用方法
//1、首先创建一个File对象file,将文件路径path传入进去
//2、使用file.exist()判断该路径表示的文件是否存在,如果存在,那么就可以对其进行操作
//3、如果不存在,那么可以使用file.createFile(),根据传入的path创建一个新文件
	    String path = "D:\\IDEA\\WorkSpace\\HelloWorld\\FailName.mp3";
        File file = new File(path);

        if(file.exists()){
            System.out.println("file.getName() = " + file.getName());
        }else{
            try{
                file.createNewFile();
                System.out.println("文件创建成功!!!");
            }catch (IOException e){
                e.printStackTrace();
            }
        }

FIle对象的常用方法:

方法名称参数列表返回值
exists()是否存在
isFile()是否为文件
isDirectory()是否为文件夹
getPath()绝对路径
getAbsolutePath()相对路径
length()文件大小,单位是字节
getName()文件名
createNewFile()Boolean,表示是否创建文件成功
listFiles()如果file的path是一个文件夹,那么返回一个文件数组,是该文件夹下的所有文件夹和文件
mkdir()Boolean,表示是否创建文件夹成功
delete删除文件
deleteOnExit不直接删除文件,而是在JVM虚拟机关闭后删除文件

try-with-resource

因为我们在使用完文件I/O流后需要手动关闭资源

在try-catch-finally结构的代码中,为了防止代码出现异常导致资源关闭失败,建议将close()方法写在finally块中

这里有一个方便的写法:

try (//输入流
     InputStream inputStream = new FileInputStream(file);
     DataInputStream dataInputStream = new DataInputStream(inputStream);
      //输出流
      OutputStream outputStream = new FileOutputStream(file1);
      DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {
            
	
}
        } catch (IOException e) {
            e.printStackTrace();
        }

将我们需要使用的I/O流资源定义在try中的小括号中,那么JVM会自动帮我们回收该资源

FileInputStream:文件输入流

使用实例:

		/**
         * 带byte[]数组参数的read()方法读取txt文件
         */
        File file = new File("D:\\IDEA\\WorkSpace\\HelloWorld\\Helloworld.txt");
        if (file.exists()) {
            //直接在try中定义好之后要释放的资源
            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                byte[] bytes = new byte[10];
                int num;
                while ((num = fileInputStream.read(bytes)) > 0) {
                    /*因为最后一次读取byte数组,可能读取的字节并不是刚好10个,
                    * 因此最后一次读取的字节只会覆盖掉原本byte数组的一部分,
                    * 所以我们创建字符串的时候需要指定byte数组的位置,
                    * 从0到read()的返回值num,也就是读取到了多少个字节的数据
                    * 只打印被覆盖掉的部分*/
                    System.out.print(new String(bytes, 0, num));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

常用方法:

方法名称参数列表返回值
readint a,表示从输入流中读取到了多少个字节

FileOutputStream:文件输出流

使用实例:

		/**
         * 使用write方法来向文件写入数据
         */
        try(FileOutputStream stream = new FileOutputStream("D:\\IDEA\\WorkSpace\\HelloWorld\\Helloworld.txt",true))		  {
            stream.write("这是我追加的数据".getBytes());
            stream.flush();//建议在每次写入之后进行刷新操作,可以立即看见写入效果
        } catch (IOException e){
            e.printStackTrace();
        }

常用方法:

方法名称参数列表返回值
writebytes,int off,int num将byte[]数组中,下标从off到num的部分写入到缓冲区中
writebyte[]将byte[]数组中的所有字节都写入到缓冲区中
flush将缓冲区中存储的所有字节手动存入到文件中,在输出流关闭的时候自动调用,不建议手动写,影响性能

注意:

  • 在FileOutputStream创建时,默认的输出方式是覆盖原有内容输出,如果我们需要在文件末尾追加输出,那么可以在构造函数中添加一个true参数,将输出方式设置为末尾添加输出
  • 如果传入的文件不存在,那么FileOutputStream会自动创建该文件

同时使用字节输入输出流进行文件的拷贝


	/**
     * @Author: 李文波
     * @Date: 2023/1/5 11:10
     * Description: 将File中的数据拷贝到file1中
     * @return: void
     */
    public static void file_Copy(File file,File file1){
        if (file.exists()) {
            //直接在try中定义好之后要释放的资源
            try (InputStream fileInputStream = new FileInputStream(file);
                OutputStream outputStream = new FileOutputStream(file1, true)) {
                byte[] bytes = new byte[1024];
                int num;
                while ((num = fileInputStream.read(bytes)) > 0) {
                    outputStream.write(bytes, 0, num);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

字符流操作


Reader基类


是所有字符输入流的父类,其下的主要实现类有:FileReader、BufferedReader

其操作和字节输入流相似:

try (Reader reader = new FileReader("D:\\IDEA\\WorkSpace\\HelloWorld\\Helloworld.txt")) {
            int num = 0;
            char[] chars = new char[1024];
            while ((num = reader.read(chars)) != -1) {
                System.out.println(new String(chars, 0, num));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

字符流和字节流在使用上唯一的不同就是将字节流的byte[]字节数组换成了char[]字符数组

Writer基类


使用Reader和Writer字节输入输出流来进行文件拷贝:

	/**
     * @Author: 李文波
     * @Date: 2023/1/5 11:35
     * Description: 使用FileReader读取文件,使用FileWriter来将其写入文件中
     * @return: void
     */
    public static void write_File(File file, File file1) {
        try (Reader reader = new FileReader(file);
             Writer writer = new FileWriter(file1)) {

            int num = 0;
            char[] chars = new char[10];

            while ((num = reader.read(chars)) != -1) {
                writer.write(chars, 0, num);
                writer.flush();//清空缓冲区
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

注意:

  • 我们在写入文件的时候需要先将文件写入缓冲区,然后等缓冲区满了再一次性写入磁盘,这样可以提高性能,因此我们使用flush()方法可以强制将缓冲区的内容写入磁盘
  • 但是这么做的话会影响性能,因此当我们一次性读取的数据量较大的时候才能这么干

BufferedReader类

/**
     * @Author: 李文波
     * @Date: 2023/1/5 14:21
     * Description: 使用BufferedReader来读取file中的数据
     * @return: void
     */
    public static void bufferedReader_Demo(File file) {
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

需要注意的是在创造BufferedReader对象的时候传入的值是Reader

BufferedWriter类

/**
     * @Author: 李文波
     * @Date: 2023/1/5 14:22
     * Description: 使用BufferedWriter来将file文件中的数据写入file1
     * @return: void
     */
    public static void bufferedWriter_Demo(File file, File file1) {
        try (FileReader fileReader = new FileReader(file);
             FileWriter fileWriter = new FileWriter(file1, true);
             BufferedReader bufferedReader = new BufferedReader(fileReader);
             BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {


            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

需要注意的是在创造BufferedWriter对象的时候传入的值是Writer

DataInputStream类

是FileInputStream的子类,可以读取二进制文件

DataOutputStream类

/**
     * @Author: 李文波
     * @Date: 2023/1/5 14:55
     * Description: 使用DataInputStream和DataOutputStream来拷贝二进制文件
     * @return: void
     */
    public static void dataOutputStream_Demo(File file, File file1) {
        try (//输入流
             InputStream inputStream = new FileInputStream(file);
             DataInputStream dataInputStream = new DataInputStream(inputStream);
             //输出流
             OutputStream outputStream = new FileOutputStream(file1);
             DataOutputStream dataOutputStream = new DataOutputStream(outputStream)) {

            int num;
            byte[] bytes = new byte[1024];
            while ((num = dataInputStream.read(bytes)) != -1) {
                dataOutputStream.write(bytes, 0, num);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

拷贝文件的方法:

  • 1、前面提到的文件流操作
  • 2、使用Java类库Files里的copy方法
OutputStream outputStream = new FileOutputStream(file1);
Files.copy(Paths.get("D:\\有用\\图片\\hutao2.jpg"), outputStream);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值