简体   繁体   中英

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

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM