Java怎样读取txt文件的内容( 三 )

测试:
public static void main(String args){ List\u0026lt;String\u0026gt; stringList = readTxtFileIntoStringArrList("C:\\\\h.log"); System.out.println("-------使用BufferedReader读取-----------"); for(String str : stringList) { System.out.println(str); } System.out.println("\---------使用byte直接缓存整个文件到内存----------------"); String stringArr = readToString("C:\\\\h.log"); for(int i = 0 ; i \u0026lt; stringArr.length ; i ++) { System.out.println(stringArr); } }结果:
-------使用BufferedReader读取----------- : RecogizeCache init : RecogizeCache init : RecogizeCache init : RecogizeCache init : 读取文件:4209bad42de0f6e55c0daf0bd24b635a.txt---------使用byte直接缓存整个文件到内存---------------- : RecogizeCache init : RecogizeCache init : RecogizeCache init : RecogizeCache init : 读取文件:4209bad42de0f6e55c0daf0bd24b635a.txt比较
  方式1是将文件的一部分或全部数据读取出来用BufferReader缓存起来,需要再冲缓存中取数据,这样比要得时候去文件中读取要快一些。
  方式2是一次把文本的原始内容直接读取到内存中再做处理(暂时不考虑内存大小),这样做效率也会提高。同时,可以处理当你使用第1方式用readLine()方法时,文件又有线程在不断的向文件中写数据【只处理现在已经在文件中的数据】。另外,用readline()之类的方法,可能需要反复访问文件,而且每次readline()都会调用编码转换,降低了速度,所以,在已知编码的情况下,按字节流方式先将文件都读入内存,再一次性编码转换是最快的方式。


■网友
读取txt文件的内容(java),如下方式供参考:public class Test {\tpublic static void read() {\t\tString string = null;\t\ttry {\t\t\t// 在给定从中读取数据的文件名的情况下创建一个新 FileReader\t\t\tFileReader fr = new FileReader("e:read.txt");\t\t\t// 创建一个使用默认大小输入缓冲区的缓冲字符输入流\t\t\tBufferedReader br = new BufferedReader(fr);\t\t\twhile (null != (string = br.readLine())) {\t\t\t\tSystem.out.println(string);\t\t\t}\t\t} catch (Exception e) {\t\t\te.printStackTrace();\t\t}\t}\tpublic static void main(String args) {\t\tread();\t}} 【Java怎样读取txt文件的内容】

■网友
很简单的比如说String path ="C:\\\\student.txt";Scanner in =new Scanner(new File(path));String content="";while(in.hasNext()){ content +=in.nextLine+"\";}这样就把内容放到content中去了。纯手打可能有打错的地方。忘记加异常处理了,在eclipse中点一下就可以直接加上。
■网友
直接去学java输入输出流的处理
■网友
最简单的使用 io流 就可以了 如果不会写代码 直接上百度搜索 如何将文件读取到内存中 然后注意编码格式就好了 防止乱码
■网友
原生的流正如上面的回答,了解原理即可,实际写起来太烦了,长且重复性工作太多。 可以使用google的guava工具包,一个静态方法一行代码搞定,Files.readlines即可,会返回每一行文字的列表,注意编码蛤,文件输出方法里面也有,同样一两行代码。。。


推荐阅读