开发者

Opening and Analyzing ASCII files

开发者 https://www.devze.com 2023-01-11 14:36 出处:网络
How do I open and read an ASCII file? I\'m working on opening and retrieving contents of the file and analying开发者_StackOverflow社区 it with graphs.Textbased files should be opened with a java.io.Re

How do I open and read an ASCII file? I'm working on opening and retrieving contents of the file and analying开发者_StackOverflow社区 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:

  • Java IO tutorial
  • Scanner tutorial


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.

0

精彩评论

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