Thursday, November 11, 2010

How to read a file in Java

Usually such kind of function is not recommended when reading huge files. Because it is not possible for java to allocate so much contigous memory.

As far a possible, avoid using this function.

public static String getFile(String filepath) 
{
        StringBuilder output = new StringBuilder("");
        try 
        {       
            File file = new File(filepath);
            FileReader fileReader = new FileReader(file);
            BufferedReader bfr = new BufferedReader(fileReader);
            String line ;
            while((line = bfr.readLine()) != null)
            {
                output.append(line + "\n");
            } 
            bfr.close();
            fileReader.close();
        }
        catch (FileNotFoundException e) 
        {
              e.printStackTrace();
        } 
        catch (IOException e) 
        {
              e.printStackTrace();
        }   
        finally
        {
            
        }
        return output.toString();
}

No comments:

Post a Comment