繁体   English   中英

如何使用 DataInputStream 从文件中读取二进制数据并打印到控制台?

[英]How to use DataInputStream to read binary data from a file and print to the console?

这是问的问题:编写一个程序,使用 DataInputStream 从 binary.txt 读取行星详细信息,并在标准输出上打印行星详细信息。

但是,下面的程序会抛出一个 IOException。 我无法弄清楚问题所在。 任何帮助,将不胜感激。

import java.io.*;

public class LA4ex2b  {
    public static void main(String[] args) throws IOException {
        DataInputStream input=null;
        try
        {
            input= new DataInputStream(new FileInputStream("C:/Users/user/workspace/LA4ex2a/binary.txt"));
            String str;
            // read until the string read is null i.e. read till end of file
            while ((str = input.readUTF()) != null) {
                String token[] = str.split(" "); // tokenizes the string with
                                                    // space as a delimeter

                for (int i = 0; i <token.length; i++)
                {
                    if (IsDouble.IsaDouble(token[i]))



System.out.print(Double.parseDouble(token[i]));
                    else
                        System.out.print(token[i]);
                }
            }


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

        finally
        {
            if (input!= null)
                input.close();
        }


    }

}

如果您正在读取二进制文件,则不能假设它是作为文本存储的。

相反,您必须事先知道每个字段数据类型是什么,并像这样阅读它们

    DataInputStream input= new DataInputStream(new FileInputStream(new File("xyz")));
    double d = input.readDouble();
    int i = input.readInt();
    char c = input.readChar();

正如你所看到的,有“水星”——行星名称——但没有双“1.23”的文本表示,所以它实际上是二进制数据。 也许input.readDouble 始终在 Internet 上搜索 javadoc。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM