java学习工作专题

9.2Java大文件读写操作

2017-06-01  本文已影响846人  孔垂云

在读写大文件, 比如超过100M或者1G的文件时,还用简单的fileinput和fileoutput是不行的,这样很容易导致内存溢出。在处理大文件的读写时,需要采用更好的方式来处理,通常来讲,是利用BufferReaderBufferWriter

读取文件的两种方式

  /**
     * 读取大文件
     *
     * @param filePath
     */
    public void readFile(String filePath) {
        FileInputStream inputStream = null;
        Scanner sc = null;
        try {
            inputStream = new FileInputStream(filePath);
            sc = new Scanner(inputStream, "UTF-8");
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (sc != null) {
                sc.close();
            }
        }
    }

    /**
     * 读取文件
     *
     * @param filePath
     */
    public void readFile2(String filePath) {
        File file = new File(filePath);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file), 5 * 1024 * 1024);   //如果是读大文件,设置缓存
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                System.out.println(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

上面讲了两种读取文件的方式,第一种是利用Scanner扫描文件,第二种利用BufferedReader设置缓冲,来读取文件。

当然在读取过程中,即System.out.println这句话进行数据的处理,而不能把文件都放到内存中。

文件写入

  /**
     * 写文件
     * @param filePath
     * @param fileContent
     */
    public void writeFile(String filePath, String fileContent) {
        File file = new File(filePath);
        // if file doesnt exists, then create it
        FileWriter fw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(fileContent);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

写文件利用BufferedWriter,可以保证内存不会溢出,而且会一直写入。

源码下载

本例子详细源码

上一篇 下一篇

猜你喜欢

热点阅读