四季花海
java提供了搞笑读取文件的方式:文件流,下面以FileInputStream和Apache Commons IO流两种读取方式来详细讲解:以下两种代码均是读取一个大约1G的文件:1、文件流FileInputStream inputStream = null;Scanner sc = null;try {inputStream = new FileInputStream(path);sc = new Scanner(inputStream, "UTF-8");while (sc.hasNextLine()) {String line = sc.nextLine();// System.out.println(line);}// note that Scanner suppresses exceptionsif (sc.ioException() != null) {throw sc.ioException();}} finally {if (inputStream != null) {inputStream.close();}if (sc != null) {sc.close();}}这种方案将会遍历文件中的所有行——允许对每一行进行处理,而不保持对它的引用。总之没有把它们存放在内存中:(大约消耗了150MB内存)2、Apache Commons IO流同样也可以使用Commons IO库实现,利用该库提供的自定义LineIterator:LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");try {while (it.hasNext()) {String line = it.nextLine();// do something with line}} finally {LineIterator.closeQuietly(it);}由于整个文件不是全部存放在内存中,这也就导致相当保守的内存消耗:(大约消耗了150MB内存)