首页 > 解决方案 > 在 Java 中使用 FileInputStream 从文件中读取文本时出现问题

问题描述

我的系统中有一个文件 input.txt,我想使用 Java 中的 FileInputStream 从该文件中读取数据。代码中没有错误,但仍然无法正常工作。它不显示输出。这是代码,任何人都可以帮助我。

package com.company;

import java.io.FileInputStream;
import java.io.InputStream;

public class Main {

    public static void main(String[] args) {
    // write your code here

        byte[] array = new byte[100];

        try {
            InputStream input = new FileInputStream("input.txt");

            System.out.println("Available bytes in the file: " + input.available());

            // Read byte from the input stream
            input.read(array);
            System.out.println("Data read from the file: ");

            // Convert byte array into string
            String data = new String(array);
            System.out.println(data);

            // Close the input stream
            input.close();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }
}

标签: javainputstreamfileinputstream

解决方案


使用实用程序类Files

    Path path = Paths.get("input.txt");
    try {
        String data = Files.readString(path, Charset.defaultCharset());
        System.out.println(data);
    } catch (Exception e) {
        e.printStackTrace();
    }

对于二进制数据,非文本,应该使用Files.readAllBytes.

  • available()不是文件长度,只是系统已经缓冲的字节数;read more 将在物理读取磁盘设备时阻塞。

  • String.getBytes(Charset)new String(byte[], Charset)明确指定实际字节的字符集。String然后将文本保留为 Unicode,因此它可以组合世界上所有的脚本。

    由于当时使用 C 和 C++ 的情况,Java 被设计为使用 Unicode 文本。因此,您可以在字符串中混合使用阿拉伯文、希腊文、中文和数学符号。对于该二进制数据( byte[], InputStream, OutputStream),必须给定编码、Charset、字节所在的字节,然后将文本( String, char, Reader, Writer) 转换为 Unicode。

  • FileInputStream.read(byte[])需要使用结果并且只读取一个缓冲区,必须重复。


推荐阅读