Java读写文件的几种方式

导读:本篇文章讲解 Java读写文件的几种方式,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前言

Java中读写文件是非常基本的IO操作了,现在总结一下常见的用法。首先总结一下读取文件的步骤:

  1. 根据文件的路径获取到文件File对象
  2. 将File对象转换成输入流InputStream
  3. 将输入流读出来,读的时候Java提供了相应的Reader类
  4. 文件流读完之后一定要关闭。

注意:本文文件的字符集都是UTF-8,如果需要字符集转换的请自行处理。

一:字节流读取方式

一般字节流读取方式用在读取图片或者固定格式文件的方式。
如果是一次读取一个字节方式可以用如下方法:

    /**
     * 以字节为单位读取文件内容,一次读取1个字节
     */
    @Test
    public void inputStream1Test() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(inputStreamFilePath));
            int len;
            while ((len = inputStream.read()) != -1) {
                System.out.write(len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

当然也可以使用缓冲区一次读多个字节

    /**
     * 以字节为单位读取文件内容,一次读取1024个字节
     */
    @Test
    public void inputStream2Test() {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(inputStreamFilePath));
            byte[] temp = new byte[1024];//设置一个1024个字节大小的缓冲区
            int byteRead;
            while ((byteRead = inputStream.read(temp)) != -1) {
                System.out.write(temp, 0, byteRead);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

二:字符流读取方式

字符流读取方式最常见的就是读取txt文件操作了,原理就是将上面的字节流转换成字符流。
代码示例:

    /**
     * InputStreamReader主要是将字节流转字符流
     */
    @Test
    public void inputStreamReadTest() {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(new FileInputStream(new File(inputStreamFilePath)));
            int len;
            while ((len = inputStreamReader.read()) != -1) {
                System.out.print((char) len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

当然字符流也是可以设置缓冲区的

    /**
     * InputStreamReader主要是将字节流转字符流,
     * 可以一次读一个缓冲区
     */
    @Test
    public void inputStreamRead2Test() {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(new FileInputStream(new File(inputStreamFilePath)));
            char[] charBuff = new char[1024];//定义一个1024个字符缓冲区大小
            int charRead;
            while ((charRead = inputStreamReader.read(charBuff)) != -1) {
                System.out.println(new String(charBuff, 0, charRead));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

三:BufferedReader方式

java中非常实用的给我们提供了缓冲区读取文件的方法,提供了BufferedReader。实用方式如下:

    /**
     * BufferedReader 默认会将字符流读到一个缓冲区,缓冲区默认大小 8192
     */
    @Test
    public void bufferReaderTest() {
        BufferedReader bufferedReader;
        try {
            bufferedReader = new BufferedReader(new FileReader(new File(inputStreamFilePath)));
            int len;
            while ((len = bufferedReader.read()) != -1) {
                System.out.print((char) len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

更方便的是BufferedReader中提供了按行读的readLine方法

    /**
     * BufferedReader 默认会将字符流读到一个缓冲区,提供readLine方法,按行读取信息
     */
    @Test
    public void bufferReader2Test() {
        BufferedReader bufferedReader;
        try {
            bufferedReader = new BufferedReader(new FileReader(new File(inputStreamFilePath)));
            String conStr;
            while ((conStr = bufferedReader.readLine()) != null) {
                System.out.println(conStr);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

三:写文件

直接使用FileOutputStream方式

    @Test
    public void outputStreamTest() {
        OutputStream outputStream = null;
        try {
            File file = new File(outputStreamFilePath);
            outputStream = new FileOutputStream(file);
            String hello = "你好,leo825,";
            outputStream.write(hello.getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

当然也可以使用直接使用BufferedOutputStream方式

    /**
     * BufferedOutputStream输出流,默认缓冲区8192
     */
    @Test
    public void bufferedOutputStreamTest() {
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {
            File inputStreamFile = new File(inputStreamFilePath);
            File outputStreamFile = new File(outputStreamFilePath);
            bufferedInputStream = new BufferedInputStream(new FileInputStream(inputStreamFile));
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputStreamFile));
            int len;
            while ((len = bufferedInputStream.read()) != -1) {
                bufferedOutputStream.write(len);
            }
            bufferedOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

四:追加文件内容

方法一:使用FileWriter

    /**
     * 向文件中追加内容
     */
    @Test
    public void appendFile1Test() {
        FileWriter fw = null;
        PrintWriter pw = null;
        try {
            File file = new File(outputStreamFilePath);
            fw = new FileWriter(file, true);
            pw = new PrintWriter(fw);
            pw.append("你好,我是追加内容1\r\n");
            pw.flush();
            fw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                pw.close();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

方法二:使用BufferedWriter进行追加

    /**
     * 使用BufferedWriter进行追加
     */
    @Test
    public void appendFile2Test() {
        BufferedWriter bufferedWriter = null;
        try {
            File file = new File(outputStreamFilePath);
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            bufferedWriter.write("你好,我是追加内容2\r\n");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

方法三:使用RandomAccessFile结合seek方法进行追加

    /**
     * 使用RandomAccessFile结合seek方法进行追加
     */
    @Test
    public void appendFile3Test() {
        RandomAccessFile randomAccessFile = null;
        try {
            File file = new File(outputStreamFilePath);
            randomAccessFile = new RandomAccessFile(file, "rw");//打开一个随机访问文件流,按照读写方式
            long fileLength = randomAccessFile.length();//文件的长度,用来寻找文件尾部
            randomAccessFile.seek(fileLength);//将写文件指针移动到文件尾部
            randomAccessFile.write("你好,我是追加内容3\r\n".getBytes());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                randomAccessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/72682.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!