Search code examples
javafileiobinarydata-storage

Reading Binary file's in JAVA


Ok so I'm learning to write and read binary file in java and this is the method I get suggested everywhere I google Here's the weighting class

    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!");
    }

Here's the reading Class

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

but then my output is t e s t "There are squares in between each char"


Solution

  • For binary, non-text, files DataInputStream/DataOutputStream are more clear.

    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 writes a length, and the an UTF-8 encoded string. A Unicode format, so any script may be written. One may mix Japanese, Greek, emoticons and Bulgarian.