try { FileInputStream fileInputStream = new FileInputStream("example.txt"); int byteRead; while ((byteRead = fileInputStream.read()) != -1) { System.out.println(byteRead); } fileInputStream.close(); } catch(FileNotFoundException e) { System.out.println("File not found."); } catch(IOException e) { System.out.println("Cannot read the file."); }
try { FileInputStream fileInputStream = new FileInputStream("example.txt"); byte[] buffer = new byte[1024]; int bytesRead = fileInputStream.read(buffer, 0, 1024); System.out.println(new String(buffer, 0, bytesRead)); fileInputStream.close(); } catch(FileNotFoundException e) { System.out.println("File not found."); } catch(IOException e) { System.out.println("Cannot read the file."); }In this example, we are reading a specific range of bytes, starting from the beginning of the file, using a buffer of size 1024 bytes. We are using the read() method, which returns the number of bytes read, and specifying the starting point and length of the bytes read. Finally, we convert the byte array to a String object and print it to the console. Package library: java.io