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

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


当前回答

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);

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

其他回答

org.apache.commons.io.FileUtils中的方法也可能非常方便,例如:

/**
 * Reads the contents of a file line by line to a List
 * of Strings using the default encoding for the VM.
 */
static List readLines(File file)

Java 11 Files.readString中引入了最直观的方法

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;

public class App {
    public static void main(String args[]) throws IOException {
        String content = Files.readString(Paths.get("D:\\sandbox\\mvn\\my-app\\my-app.iml"));
        System.out.print(content);
    }
}

PHP几十年来一直享有这种特权!☺

使用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();
}

这里有另一种不使用外部库的方法:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public String readFile(String filename)
{
    String content = null;
    File file = new File(filename); // For example, foo.txt
    FileReader reader = null;
    try {
        reader = new FileReader(file);
        char[] chars = new char[(int) file.length()];
        reader.read(chars);
        content = new String(chars);
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if(reader != null){
            reader.close();
        }
    }
    return content;
}

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

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

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