How to Read 1st line of a file with BufferedReader?

谁说胖子不能爱 提交于 2020-01-03 04:48:07

问题


I was experimenting with BufferedReader to read 1st line file to a string. How do I do this? Also how can I read an entire file to a string? How to read a particular line like readline(int line) without iterating through the previous lines?

File namefile = new File(root, ".name");
FileReader namereader = new FileReader(namefile);
BufferedReader in = new BufferedReader(namereader);

回答1:


You can use BufferedReader.readLine() to get the first line.

Note that the next call to readLine() will get you the 2nd line, and the next the 3rd line....

EDIT:
If you want to specify a specific line, as your comment suggest - you might want to use Apache Commons FileUtils, and use: FileUtils.readLines(). It will get you a List<String> which you can handle like any list, including getting a specific line. Note that it has more overhead because it reads the entire file, and populates a List<String> with its lines.




回答2:


Um, what's wrong with BufferedReader.readLine()?

Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

(I don't see any sign of a readFile() method though - what documentation were you looking at?)

Personally I prefer to use FileInputStream wrapped in InputStreamReader instead of FileReader by the way, as otherwise it will always use the platform default encoding - are you sure what's what you want?




回答3:


final File namefile = new File(root, ".name");
final FileReader namereader = new FileReader(namefile);
final BufferedReader in = new BufferedReader(namereader);
in.readLine();



回答4:


If you use the BufferedReader to read the File there should be a Method called

readLine()

wich reads exactly one Line.

http://developer.android.com/reference/java/io/BufferedReader.html




回答5:


See the readline() method of the BufferedReader.

http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine%28%29



来源:https://stackoverflow.com/questions/9431970/how-to-read-1st-line-of-a-file-with-bufferedreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!