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

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


当前回答

使用BufferedReader:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

BufferedReader br;
try {
    br = new BufferedReader(new FileReader("/fileToRead.txt"));
    try {
        String x;
        while ( (x = br.readLine()) != null ) {
            // Printing out each line in the file
            System.out.println(x);
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
catch (FileNotFoundException e) {
    System.out.println(e);
    e.printStackTrace();
}

其他回答

对于使用Kotlin的Android开发者来说:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val text = myFileUrl.readText() // Not recommended for huge files
println(text)

其他解决方案:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
val lines = file.readLines() // Not recommended for huge files
lines.forEach(::println)

另一个很好的解决方案,也可以用于大文件:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file
    .bufferedReader()
    .lineSequence()
    .forEach(::println)

Or:

val myFileUrl = object{}.javaClass.getResource("/vegetables.txt")
val file = File(myFileUrl.toURI())
file.useLines { lines ->
    lines.forEach(::println)
}

注:

txt文件应该在您的类路径中(例如,在src/main/resources目录中) 上述解决方案都默认将文件编码处理为UTF-8。您可以指定所需的编码作为函数的参数。 上述解决方案不需要任何进一步的操作,如关闭文件或读取器。它们由Kotlin标准库自动处理。

这里有一个简单的解决方案:

String content = new String(Files.readAllBytes(Paths.get("sample.txt")));

或读作列表:

List<String> content = Files.readAllLines(Paths.get("sample.txt"))

我最喜欢的读取小文件的方法是使用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);

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

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