0

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

  • 3
    use a StringBuilder rather than a String for `all` – Scary Wombat Jun 28 '17 at 02:44
  • 1
    Check this https://stackoverflow.com/questions/16104616/using-bufferedreader-to-read-text-file – Deepak Kumar Jun 28 '17 at 02:46
  • For reading file line by line, use `java.util.Scanner.hasNextLine()` and `nextLine`. It doesn't read all lines into memory. Tutorial http://www.baeldung.com/java-read-lines-large-file – Jay Smith Jun 28 '17 at 03:17
  • I am also new to java. But focusing on the point "How does Buffer Reader works??".. When we decrypt your file the memory that is present in Hard disk is passed to the RAM through a stream then it gets decrypted . After getting decrypted we have to again send back to the hard disk as we have to store it. So, for doing that we use file reader, but it works slowly and sends data one by one through the stream. So a buffer is made with the help of buffer reader which makes the w transfer faster as it makes a buffer of the data to be sent.. – Mansit Suman Jun 28 '17 at 02:52

2 Answers2

3

Stream it, don't read it into memory. Also, I would prefer a try-with-resources (because you need to close your resources). And you can always adjust the buffer size, for example -

final int size = 1024 * 1024;
try (BufferedReader br = new BufferedReader(new FileReader("myfile.txt"), size)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line); // <-- stream it
    }
} catch (Exception e) {
    e.printStackTrace();
}

And never swallow Exception(s) - "nope" isn't very helpful.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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!

Isha Agarwal
  • 420
  • 4
  • 12