Reading a file using FileInputStream
To read a file using FileInputStream
in Java, follow these steps:
- Import the necessary packages:
1 2 | import java.io.FileInputStream; import java.io.IOException; |
2. Create a FileInputStream
object for the file you want to read:
1 | FileInputStream fis = new FileInputStream("filename.txt"); |
3. Create a buffer array to store the data you read from the file:
1 | byte[] buffer = new byte[1024]; |
4. Use the read
method of the FileInputStream
class to read data from the file into the buffer:
1 | int bytesRead = fis.read(buffer); |
The read
method returns the number of bytes read from the file, or -1
if the end of the file has been reached.
5. Use the data you have read from the file, for example by converting it to a string:
1 | String fileData = new String(buffer, 0, bytesRead); |
6. Close the FileInputStream
object to release any system resources it is holding:
1 | fis.close(); |
Here is an example that reads the contents of a file and prints them to the console:
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 | package ebhor.io; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileInputStreamClass { public static void main(String[] args) { FileInputStream fis = null; int data; try { fis = new FileInputStream("D://first.txt"); while ((data = fis.read()) != -1) { System.out.print((char) data); } } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException " + ex); } catch (IOException ex) { System.out.println("IOException " + ex); } finally { try { if (fis != null) { fis.close(); } } catch (Exception ex) { System.out.println("Exception " + ex); } } } } |