Search code examples
javafileinputbufferedreaderfilereader

read from a file using BufferedReader, and FileReader


I am relatively new to java, and am curious as to how to read from a file using buffered reader. the reason for this is i'm taking a class and was assigned to do a simple ceaser cipher, I'm supposed to decrypt a text file, create a new file, and put the decrypted text into that file. I was able to do this with the scanner, and a small 10KB file, but it was extremely slow when working with the big 100MB text file i'm gonna be tested with. here is the code i have which is supposed to read the file contents.

public static void main(String[] args)
{
    BufferedReader br = null;
    FileReader file = null;
    String line = null;
    String all = null;
    try
    {
        file = new FileReader("myfile.txt");
        br = new BufferedReader(file);
        while ((line = br.readLine()) != null) {
            all += line;
        }
    }catch(Exception e)
    {
        System.out.println("nope");
    }
    System.out.println(all);

}

if someone could point me in the right direction, that would be fantastic.

thanks in advance


Solution

  • Strings in Java are immutable, so everytime when this code is run

    all += line;
    

    It creates a new String and assigns to all, use StringBuider or StringBuffer

    For eg

    StringBuilder all = new StringBuilder();
    

    Hope it helps!