Showing posts with label read file. Show all posts
Showing posts with label read file. Show all posts

Tuesday, 10 May 2011

Read File in String Using Java BufferedInputStream Example

public static String readFile(String fileName){
File file = new File(fileName);
BufferedInputStream bin = null;

try
{
//create FileInputStream object
FileInputStream fin = new FileInputStream(file);

//create object of BufferedInputStream
bin = new BufferedInputStream(fin);

//create a byte array
byte[] contents = new byte[1024];

int bytesRead=0;
String strFileContents;
StringBuffer buf= new StringBuffer();

while( (bytesRead = bin.read(contents)) != -1){

strFileContents = new String(contents, 0, bytesRead);
buf.append(strFileContents)
System.out.print(strFileContents);
}
return buf.toString();
}
catch(FileNotFoundException e)
{
System.out.println("File not found" + e);
}
catch(IOException ioe)
{
System.out.println("Exception while reading the file "
+ ioe);
}
finally
{
//close the BufferedInputStream using close method
try{
if(bin != null)
bin.close();
return String.Empty();
}catch(IOException ioe)
{
System.out.println("Error while closing the stream :"
+ ioe);
return String.Empty();
}

}
}


File name can be "C://FileIO//ReadFile.txt".

Java: read a text file line by line

This class reads a text file line by line and echos the contents to standard out.
Here we have used BufferedReader to do this.
import java.io.*;

public static String readFile(String fileName)
// nested initialization,
// or in design pattern jargon, decorate FileInputStream with
// BufferedInputStream.
BufferedReader in = new BufferedReader(new FileReader(fileName));
try {
// read file line by line
String line = in.readLine();
while (line != null) {
printLine(line);
line = in.readLine();
}
}
finally {
// always close input stream
in.close();
}
}
private static void printLine(String line) {
System.out.println(line);
}