java - 无法逐行读取txt文件

标签 java file-io nio

<分区>

我试图在每一行中读取一个 txt 文件(里面有文本)。然后我稍后会处理这些行。

这是我的作品。

 import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class Fypio {

    public static void main(String args[]) {

        String fileName = "e://input.txt";

        //read file into stream, try-with-resources
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

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

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

但是,我收到以下错误。不过,我绝对确定该目录是正确的。

错误:

Exception in thread "main" java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
  at java.io.BufferedReader$1.hasNext(BufferedReader.java:574)
  at java.util.Iterator.forEachRemaining(Iterator.java:115)
  at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
  at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
  at fypio.Fypio.main(Fypio.java:21)
Caused by: java.nio.charset.MalformedInputException: Input length = 1
  at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
  at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
  at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
  at java.io.InputStreamReader.read(InputStreamReader.java:184)
  at java.io.BufferedReader.fill(BufferedReader.java:161)
  at java.io.BufferedReader.readLine(BufferedReader.java:324)
  at java.io.BufferedReader.readLine(BufferedReader.java:389)
  at java.io.BufferedReader$1.hasNext(BufferedReader.java:571)
  ... 4 more

#或者可以提供任何示例代码来逐行读取txt文件?

更新我的 txt 文件应该用 ANSI 编码

最佳答案

MalformedInputException表示您的文本文件不在 charset 中(编码)你要求的。

尽管您的代码没有明确指定字符集,Files.lines method always uses UTF-8 :

Read all lines from a file as a Stream. Bytes from the file are decoded into characters using the UTF-8 charset.

由于您的文本文件不是 UTF-8 文本文件,因此您需要 specify its charset在你的代码中。如果您不确定,该文件可能使用了系统的默认字符集:

try (Stream<String> stream = Files.lines(Paths.get(fileName), Charset.defaultCharset())) {

更新:

您在评论中声明您的文本文件是“ANSI”,这是 Windows 用于其单字节字符集的(技术上不正确的)名称。在美国版 Windows 上,您可能想要使用:

try (Stream<String> stream = Files.lines(Paths.get(fileName), Charset.forName("windows-1252"))) {

关于java - 无法逐行读取txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43725563/

相关文章:

java - "0"作为浮点文字中的前缀是什么意思?

java - 通信链路故障 JDBC Java

Java:从磁盘写入/读取 map

java - 仅通过一个 SocketChannel 发送多条消息

java - java.nio.file.Files 和 java.io.File 之间的区别?

java - 如何在数据库中实现 Facebook 好友模块?

java - 在 java 中处理 List<Interface> 而不进行类型转换

file-io - rayon::str::Lines <'_' > 不是迭代器

java - java socket程序中的ArrayIndexOutOfBounds异常

Java NIO : reading variable-sized blocks