I read bytes from a binary file. When reading, I convert byte 0 to character 0, byte 1 to character 1. But in this line

OP[i] = (char)((f1[i] == 0) ? '0' : '1'); 

an error occurs, the compiler says that char cannot be converted to a String. I do not understand what I did wrong. Help me find a bug.

 String OPER = "00100011101"; byte[] bytes = new byte[OPER.length()]; for (int i = 0; i < OPER.length(); i++) { bytes[i] = (byte) ((OPER.charAt(i) == '0') ? 0 : 1); //System.out.println(bytes[i]); } try (FileOutputStream fos = new FileOutputStream(new File("someFile.dat"))) { fos.write(bytes); fos.close(); } FileInputStream f1 = new FileInputStream("someFile.dat"); int size = f1.available(); String[] OP = new String[size]; System.out.println("Total Available Bytes: " + size); for (int i = 0; i < size; i++) { OP[i] = (char)((f1[i] == 0) ? '0' : '1'); System.out.print( f1.read()); } 

    2 answers 2

    Maybe in double quotes to take. I don’t know how it is in Java, but in C ++ the strings (pointer to char) are in double quotes, and char is in single quotes.

    • I tried. writes the same: array required, but FileInputStream found incompatible types: String cannot be converted to char - compl
    • one
      (char) also remove OP [i] = ((f1 [i] == 0)? "0": "1"); - dzukp

    UPDATED

      FileInputStream f1 = new FileInputStream("someFile.dat"); int size = f1.available(); char[] OP = new char[size]; byte[] singleByte = new byte[1]; System.out.println("Total Available Bytes: " + size); for (int i = 0; i < size; i++) { int readed = fi.read(singleByte) OP[i] = (char)((singleByte[0] == 0) ? '0' : '1'); System.out.print( singleByte[0]); } String result = new String(OP); 
    • Happened. But now this error: array required, but FileInputStream found - compl
    • @compl updated - Deadkenny
    • Thank! But now the compiler writes: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at decoder_parser.Decoder_parser.main(Decoder_parser.java:68) Java Result: 1 - compl
    • one
      @compl damn. byte [] singleByte = new byte [1]; Ocepchatka - Deadkenny
    • @Deadkenny, thanks! Now everything works. But I don’t fully understand why readed is needed and why the singleByte byte array has dimension 1. - compl