【问题标题】:Reading Binary file's in JAVA用JAVA读取二进制文件
【发布时间】:2021-07-26 17:56:41
【问题描述】:

好的,所以我正在学习用 java 编写和读取二进制文件,这是我在谷歌的任何地方都得到建议的方法 这是加权类

    public Writer(String fileName, String text) throws IOException {
        ObjectOutputStream output = null;
        try{
            output = new ObjectOutputStream(new FileOutputStream(fileName, true));
        } catch (FileNotFoundException e) {
            System.out.println("File not found!");
            System.exit(0);
        } catch (IOException e) {
            System.out.println("IO Exception!!");
            System.exit(0);
        }//THE TEXT HERE IS "test"
        output.writeChars(text);
        output.close();
        System.out.println("Successful writing!");
    }

这是阅读课

    public Reader(String fileName) throws IOException {
         ObjectInputStream in = null;
         try {
             in = new ObjectInputStream(new FileInputStream(fileName));
         } catch (FileNotFoundException e) {
             System.out.println("File Not found!");
             System.exit(0);
         } catch (IOException e) {
             System.out.println("IO Exception!!");
             System.exit(0);
         }
         int i;
         while ((i = in.read()) != -1){
             System.out.print((char) i);
         }
         in.close();
    }

但是我的输出是 t e s t "There are squares in between each char"

【问题讨论】:

  • 您使用writeChars 写入字符,因此您应该使用readChar() 再次读取它们。方块可能是 \0 (NUL) 字符,由每个字符写入 2 个字节引起。
  • 你正在读取字节;字符不是字节。这就是为什么有不同的方法来读取“二进制”数据和“文本”数据的原因之一。
  • ObjectInput/OutputStream 用于java对象,也存储类信息。对于二进制数据 Input/OutputStream 就足够了。对于结构化二进制数据,可以使用 ByteBuffer 或 DataInput/OutputStream。
  • @JoopEggen 能否给个代码示例

标签: java file io binary data-storage


【解决方案1】:

对于二进制、非文本文件,DataInputStream/DataOutputStream 更清晰。

try (FileOutputStream fos = new FileOutputStream("test.bin");
        DataOutputStream dos = new DataOutputStream(fos)) {
    dos.writeUTF8("La projekto celas ŝtopi breĉojn en Vikipedio");
    dos.writeInt(42);
    dos.writeDouble(Math.PI);
}

try (FileInputStream fis = new FileInputStream("test.bin");
        DataInputStream dis = new DataInputStream(fis)) {
    String s = dis.readUTF8(); // "La projekto celas ŝtopi breĉojn en Vikipedio"
    int n = dis.readInt(); // 42
    double pi = dis.readDouble() // Math.PI
}

writeUTF8 写入一个长度和一个 UTF-8 编码的字符串。 Unicode 格式,因此可以编写任何脚本。可以混合使用日语、希腊语、表情符号和保加利亚语。

【讨论】:

    猜你喜欢
    • 2011-07-25
    • 1970-01-01
    • 2015-07-27
    • 2014-12-19
    • 1970-01-01
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多