Change the following line b[j] = (char) i; on b[j] = (byte) i; .
This will give you another compiler error. But the first problem will be solved.
The first one does not work because Java uses Unicode for type char , therefore it has two bytes. You throw the int value into char , but then try to assign it to the byte variable, and for this you need to explicitly point to byte , it is no longer C or C ++.
You can also consider using the simpler fin.read(b) method, which will read up to 100 bytes in your case and return -1 when EOF is reached. Thus, you do not need to explicitly point i to a byte .
For example, for example:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; class IO { public static void main(String args[]) { byte[] b = new byte[100]; try (FileInputStream fin = new FileInputStream("file.txt");) { while (true) { int i = fin.read(b); if (i < 0) { break; } if (i < b.length) { b = Arrays.copyOf(b, i); } System.out.println(Arrays.toString(b)); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
source share