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

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


当前回答

到目前为止,我还没有在其他答案中看到它。但是如果“最佳”意味着速度,那么新的Java I/O (NIO)可能提供最快的性能,但对于初学者来说并不总是最容易理解的。

http://download.oracle.com/javase/tutorial/essential/io/file.html

其他回答

我最喜欢的读取小文件的方法是使用BufferedReader和StringBuilder。它非常简单和切中要害(虽然不是特别有效,但对大多数情况来说已经足够好了):

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
} finally {
    br.close();
}

有人指出,在Java 7之后,你应该使用try-with-resources(即自动关闭)功能:

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    StringBuilder sb = new StringBuilder();
    String line = br.readLine();

    while (line != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
        line = br.readLine();
    }
    String everything = sb.toString();
}

当我读取这样的字符串时,我通常希望每行都做一些字符串处理,所以我选择了这个实现。

虽然如果我只是想将文件读入字符串,我总是使用Apache Commons IO和类IOUtils.toString()方法。你可以在这里查看源代码:

http://www.docjar.com/html/api/org/apache/commons/io/IOUtils.java.html

FileInputStream inputStream = new FileInputStream("foo.txt");
try {
    String everything = IOUtils.toString(inputStream);
} finally {
    inputStream.close();
}

在Java 7中甚至更简单:

try(FileInputStream inputStream = new FileInputStream("foo.txt")) {     
    String everything = IOUtils.toString(inputStream);
    // do something with everything string
}
try (Stream<String> stream = Files.lines(Paths.get(String.valueOf(new File("yourFile.txt"))))) {
    stream.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

新文件(< path_name >)

通过将给定的路径名字符串转换为抽象路径名来创建一个新的File实例。如果给定的字符串是空字符串,那么结果就是空的抽象路径名。 参数: pathname -路径名字符串 抛出: NullPointerException -如果路径名参数为空

文件。lines返回String流

Stream<String> Stream = Files.lines(路径。get(字符串。返回对象的值(新文件(“yourFile.txt”)))) 可以抛出nullpointerexction, FileNotFoundException,所以,保持它在尝试将照顾异常在运行时

stream.forEach(System.out::println);

这用于在控制台中迭代流和打印 如果您有不同的用例,您可以提供您的自定义函数来操作行流

Cactoos提供了一个声明性的一行代码:

new TextOf(new File("a.txt")).asString();

对于基于jsf的Maven web应用程序,只需使用ClassLoader和Resources文件夹读取任何你想要的文件:

Put any file you want to read in the Resources folder. Put the Apache Commons IO dependency into your POM: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> Use the code below to read it (e.g. below is reading in a .json file): String metadata = null; FileInputStream inputStream; try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); inputStream = (FileInputStream) loader .getResourceAsStream("/metadata.json"); metadata = IOUtils.toString(inputStream); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return metadata;

您可以对文本文件、.properties文件、XSD模式等执行相同的操作。

这可能不是问题的确切答案。这只是读取文件的另一种方式,其中不需要在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。