java 如何读取大文件

来源:互联网 发布:泰坦尼克号电影知乎 编辑:程序博客网 时间:2024/05/20 09:23

总结一下应该只用jdk直接实现的话应该有3中方法:

1 使用Scanner类,每次读取一行。

public static void testScannerReadFile() {        FileInputStream fileInputStream = null;        Scanner scanner = null;        try {            fileInputStream = new FileInputStream("D:/test.log");            scanner = new Scanner(fileInputStream, "UTF-8");            while (scanner.hasNext()) {                String line = scanner.nextLine();                System.out.println(line);            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } finally {            if (fileInputStream != null) {                try {                    fileInputStream.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (scanner != null) {                scanner.close();            }        }    }



2 使用BufferedReader类设置一定的缓存,依然每次读取一行。

public static void readCache() {        String filename = "D:/test.log";        File file = new File(filename);        BufferedReader reader = null;        try {            reader = new BufferedReader(new FileReader(file), 10 * 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();                }            }        }    }


3 使用RandomAccessFile或内存映射

http://blog.csdn.net/akon_vm/article/details/7429245

0 0