Recently I have seen some questions about reading text file content on the OTN forum, though it is a very simple task still some find it confusing. That’s why here I am showing how to read text files in java using FileInputStream
This is a sample text file
and here goes the java code to read text file using FileInputStream
- package client;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- public class ReadFileJava {
- public ReadFileJava() {
- super();
- }
- public static void main(String[] args) {
- // Absolute path of file that you want to read
- File f = new File("D:/sampleFile.txt");
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(f);
- int data;
- //Iterate over file content
- while ((data = fis.read()) != -1) {
- System.out.print((char) data);
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- } finally {
- try {
- if (fis != null)
- fis.close();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
- }
Run this code
And output is
Cheers Happy Learning
No comments :
Post a Comment