开发者

what is the best way to read single line files in Java

Is it necessary to create buffered reader while loop and all to read single line file? its also constan开发者_开发问答t never changes


Here is how I would do it:

String txt = new Scanner(new File(path)).useDelimiter("\\Z").next();

This will read an entire file into the String.

Let me break that down for you:

String txt = // the resulting String is stored here
new Scanner( // Create a scanner to read the file
new File( "pathToFile" ) ) // pass a new file to the scanner to read
.useDelimiter("\\Z") // set the delimiter to the end of the file
.next(); // read the scanner until the next delimiter, 
         // in this case it is the end of the file.


java.util.Scanner makes it easier to read files. Also remember org.apache.commons.io.FileUtils


If you don't care about correct character conversion you could use InputStream, rather than using the Reader classes:

A performance discussion:

http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly


As the title itself says, is it necessary to create buffered reader while loop and all to read single line file? its also constant never changes

No it is not absolutely necessary, if the file is really always a single line and never changes.

  1. If the file is really always a single line, you could just read the first line; i.e. no need to loop.

  2. If the file really never changes, you may not even need to read it; i.e. you could embed the single line contents in the program itself.

However, in reality, both of your assumptions are probably false. There is always the possibility that the file might contain more lines (or be empty) or that it might contain something different to what you expect. At the very least, it would be a good idea if your program at least checked that its assumptions were not invalid. For example:

BufferedReader br = ...

// Read contents of a 1 line file.
String line = br.readLine();
if (line == null || line.length() == 0) {
    System.out.println("where's my input?");
} else if (br.readLine() != null) {
    System.out.println("too much input!");
} else {
    ...
}

In addition, as others have mentioned, there other ways of reading / parsing input that may work better than simply using a BufferedReader. It depends on what you are doing with the line you are reading from the file.

EDIT

Is there something in java like include in php?

Not in the core libraries. But IIRC there is an Apache commons utility class called FileUtils that has various methods for doing this kind of thing. For example, there are methods that read an entire file as a byte array or string, and another that reads the file and returns the lines as an array of strings.

(But hey, why would you add a 3rd-party dependency for something as trivial as this? It is only half a dozen lines of Java code to do the job properly yourself!!)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜