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);
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.
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?
final File namefile = new File(root, ".name");
final FileReader namereader = new FileReader(namefile);
final BufferedReader in = new BufferedReader(namereader);
in.readLine();
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
See the readline() method of the BufferedReader.
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/BufferedReader.html#readLine%28%29
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.