Sunday, November 19, 2017

How to Read a file

Read a File:

1) Java has a concept of working with streams of data.
2) You can say that a Java program reads sequences of bytes from an input stream (or writes into an output stream):
byte after byte,character after character,primitive after primitive.
3) Accordingly, Java defines various types of classes supporting streams,
for example, InputStream or OutputStream.
There are classes specifically meant for reading character streams such as Reader and Writer.


A Java application opens a file by creating an object and associating a stream of bytes with that object.
Similarly, when you finished using a file, the program should close the file—that is, make it no longer available to your application.



Class
Description
InputStream
Abstract class containing methods for performing input
OutputStream
Abstract class containing methods for performing output
FileInputStream
Child of InputStream that provides the capability to read from disk files
FileOutputStream
Child of OutputStream that provides the capability to write to disk files
PrintStream
Child of FilterOutputStream, which is a child of OutputStream; PrintStream handles output to a system’s standard (or default) output device, usually the monitor
BufferedInputStream
Child of FilterInputStream, which is a child of InputStream; BufferedInputStream handles input from a system’s standard (or default) input device, usually the keyboard

READING FROM A FILE
We will write a java program to read from file and print file data on the user screen. 
Let’s understand way to associate a File object with the input stream:
You can pass the filename to the constructor of the FileInputStream class.
You can create a File object by passing the filename to the File constructor.
 Then, you can pass the File object to the constructor of the FileInputStream class.
The second method has some benefits:
If you create a File object, you can use the File class methods, such as exists()and lastModified(), to retrieve file information. (Refer File Input Output Tutorial).

While working with stream classes we have to take care of checked exceptions, In our program, we are doing it using a try-catch block.

package com.coding.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadDataFromFile {

public static void main(String[] args) {
// TODO Auto-generated method stub

File file = new File("C:/Users/Remash/workspace/Coding_Project/src/com/coding/core/Data.txt");
try (FileInputStream fis = new FileInputStream(file))
{
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}

}

}



No comments:

Post a Comment

How to remove duplicate elements from an ArrayList in Java

How to remove duplicate elements from an ArrayList in Java. Ø   ArrayList allows adding duplicate elements, sometime there may be...