fos.txt file content:
public class FileInputStreamDemo { public static void main (String [] args) throws IOException { // Create byte input stream object FileInputStream fis = new FileInputStream ("myFile \\ fos.txt" ); // Call byte input stream object The method of reading data // first reading int by = fis.read (); System.out.println (by); // 97 System.out.println (( char ) by); // a // second Secondary reading by = fis.read (); System.out.println (by); // 98 System.out.println (( char)by); //b } }
By calling the read method twice and found that the code is too repetitive, can it be improved using loops? If you want to use the loop, you need to know what the end condition of the loop is. You can see it through the help documentation. When you read the end of the stream, it will return -1.
Improve reading by looping:
Modify fos.txt:
Improved code:
// Improve reading data by loop int by; while ((by = fis.read ())! = -1 ) { System.out.print (( char ) by); } // Release resources fis.close () ;
Operation result: