简体   繁体   中英

Opening and Analyzing ASCII files

How do I open and read an ASCII file? I'm working on opening and retrieving contents of the file and analying it with graphs.

Textbased files should be opened with a java.io.Reader . Easiest way would be using a BufferedReader to read it line by line in a loop.

Here's a kickoff example:

BufferedReader reader = null;

try {
    reader = new BufferedReader(new FileReader("/path/to/file.txt"));
    for (String line; (line = reader.readLine()) != null;) {
        // Do your thing with the line. This example is just printing it.
        System.out.println(line); 
    }
} finally {
    // Always close resources in finally!
    if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}

To breakdown the file content further in tokens, you may find a Scanner more useful.

See also:

Just open the file via the java.io methods. Show us what you've tried first, eh?

Using Guava , you could:

String s = Files.toString(new File("/path/to/file"), Charsets.US_ASCII));

More information in the javadoc .

It's probably enormous overkill to include the library for this one thing. However there are lots of useful other things in there. This approach also has the downside that it reads the entire file into memory at once, which might be unpalatable depending on the size of your file. There are alternative APIs in guava you can use for streaming lines too in a slightly more convenient way than directly using the java.io readers.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM