File Reading will be a part of any project or application.
Depending on the requirements, there may be need to either read the file line by line or character by character or word by word.
The below program has three methods which can perform each task separately.
Grab your method and start Coding!!!
Program
Depending on the requirements, there may be need to either read the file line by line or character by character or word by word.
The below program has three methods which can perform each task separately.
Grab your method and start Coding!!!
Program
import
java.io.BufferedReader;
import
java.io.DataInputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileNotFoundException;
import
java.io.FileReader;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.util.Scanner;
/**
* This program is used to play around with
different methods of File Reading
* @author Nijin Vinodan
*
*/
public class
FilesReader {
/**
* This method is used to read file line by
line
* @param fileName
*/
public void
readFileLineByLine(String fileName){
try{
FileInputStream
fstream = new FileInputStream(fileName);
DataInputStream
in = new DataInputStream(fstream);
BufferedReader
br = new BufferedReader(new InputStreamReader(in));
String
strLine;
while
((strLine = br.readLine()) != null){
System.out.println(strLine);
}
in.close();
}
catch(FileNotFoundException
e){}
catch(IOException
e){}
}
/**
* This method is used to read file character
by character
* @param fileName
*/
public void
readFileLetterbyLetter(String fileName){
FileInputStream
fileInput;
try {
fileInput
= new FileInputStream(fileName);
int
read;
while
((read = fileInput.read()) != -1) {
char c = (char) read;
System.out.println(c);
}
fileInput.close();
}
catch
(FileNotFoundException e) {}
catch
(IOException e) {}
}
/**
* This method is used to read file word by
word
* @param fileName
*/
public void
readFileWordByWord(String fileName){
File file = new
File(fileName);
try {
Scanner
scanInput = new Scanner(new FileReader(file));
while(scanInput.hasNext()){
System.out.println(scanInput.next());
}
scanInput.close();
}
catch
(FileNotFoundException e) {}
}
}
No comments:
Post a Comment