In this Java IO Tutorial, we will learn how to use FileInputStream to read a text file by byte-by-byte, by chunck of Bytes. We will also see how to read entire file content in one go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
01) Add Private Member //Sample 004.1: Member variables private FileInputStream fin; 02) Add Code in the Constructor //Sample 004.2: Create the File Input Stream fin = new FileInputStream("/temp/sample.txt"); 03) Handler Code for Read Byte //Sample 004.3: Read single byte from the Stream and Display it char c; c = (char) fin.read(); TA.append(String.valueOf(c)); 04) Read Bytes Handler Code //Sample 004.4: Create a Byte Array with the specified Length int bytesToRead = Integer.parseInt(txtNoOfBytes.getText()) ; byte[] data = new byte[bytesToRead]; //Sample 004.5: Read group of bytes from the Stream fin.read(data); String str = new String(data); TA.append(str); 05) Read All Button Handler //Sample 004.6: Read All int data = 0; while ((data = fin.read()) != -1) { char c = (char) data; TA.append(String.valueOf(c)); } 06) Close Button Handler //Sample 004.7: Close the File Stream fin.close(); System.exit(0); |
Categories: Java-Tube