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".

No comments:

Post a Comment