简体   繁体   English

打开和分析ASCII文件

[英]Opening and Analyzing ASCII files

How do I open and read an ASCII file? 如何打开和读取ASCII文件? 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 . 基于文本的文件应使用java.io.Reader打开。 Easiest way would be using a BufferedReader to read it line by line in a loop. 最简单的方法是使用BufferedReader在循环中逐行读取它。

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. 要使用令牌进一步细分文件内容,您可能会发现Scanner更有用。

See also: 也可以看看:

Just open the file via the java.io methods. 只需通过java.io方法打开文件。 Show us what you've tried first, eh? 告诉我们您首先尝试了什么,是吗?

Using Guava , you could: 使用Guava ,您可以:

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

More information in the javadoc . 有关更多信息,请参见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. 番石榴中还有其他API,与直接使用java.io阅读器相比,您也可以以一种更方便的方式将其用于流线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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