在Java中,似乎有不同的方式来读取和写入文件数据。

我想从一个文件读取ASCII数据。可能的方式和它们的区别是什么?


当前回答

可能没有缓冲I/O那么快,但是非常简洁:

    String content;
    try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
        content = scanner.next();
    }

\Z模式告诉扫描器分隔符是EOF。

其他回答

可能没有缓冲I/O那么快,但是非常简洁:

    String content;
    try (Scanner scanner = new Scanner(textFile).useDelimiter("\\Z")) {
        content = scanner.next();
    }

\Z模式告诉扫描器分隔符是EOF。

ASCII是一个文本文件,因此您可以使用reader进行读取。Java还支持使用InputStreams从二进制文件中读取。如果要读取的文件很大,那么您可能希望在FileReader之上使用BufferedReader来提高读取性能。

阅读这篇关于如何使用Reader的文章

我还推荐你下载并阅读这本很棒(但免费)的书,叫做《用Java思考》

在Java 7中:

new String(Files.readAllBytes(...))

(文档) 或

Files.readAllLines(...)

(文档)

在Java 8中:

Files.lines(..).forEach(...)

(文档)

try {
  File f = new File("filename.txt");
  Scanner r = new Scanner(f);  
  while (r.hasNextLine()) {
    String data = r.nextLine();
    JOptionPane.showMessageDialog(data);
  }
  r.close();
} catch (FileNotFoundException ex) {
  JOptionPane.showMessageDialog("Error occurred");
  ex.printStackTrace();
}

在实践中,缓冲流类的性能要高得多,以至于NIO.2 API包含了专门返回这些流类的方法,部分原因是为了鼓励您始终在应用程序中使用缓冲流。

这里有一个例子:

Path path = Paths.get("/myfolder/myfile.ext");
try (BufferedReader reader = Files.newBufferedReader(path)) {
    // Read from the stream
    String currentLine = null;
    while ((currentLine = reader.readLine()) != null)
        //do your code here
} catch (IOException e) {
    // Handle file I/O exception...
}

您可以替换此代码

BufferedReader reader = Files.newBufferedReader(path);

BufferedReader br = new BufferedReader(new FileReader("/myfolder/myfile.ext"));

我推荐这篇文章来学习Java NIO和IO的主要用途。

这可能不是问题的确切答案。这只是读取文件的另一种方式,其中不需要在Java代码中显式指定文件的路径,而是将其作为命令行参数读取。

使用以下代码,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class InputReader{

    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s="";
        while((s=br.readLine())!=null){
            System.out.println(s);
        }
    }
}

只需继续运行它,使用:

java InputReader < input.txt

这将读取input.txt的内容并将其打印到控制台。

你也可以让System.out.println()通过命令行写入一个特定的文件,如下所示:

java InputReader < input.txt > output.txt

这将从input.txt读取并写入output.txt。