Search code examples
javaarraysmultidimensional-arraytostringfile-handling

File to String Null Pointer Exception


I'm trying to pass the contents of a file into a method as a String and encountering a Null pointer exception. I'm converting the file into a String like so:

import java.io.*;

public class FileHandler {

    String inputText = null;

    public String inputReader() {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("in.txt"))));
            String line = null;

            while ((line = br.readLine()) != null) {
                sb.append(line);
                String inputText = sb.toString();
                //System.out.println(inputText);
            }
            br.close();

        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
        }

        return inputText;
    }
}

This is working fine for me in terms of converting the file to a String, but when I try and pass the output of this into another method I get a null pointer exception here:

                char[][] railMatrix = new char[key][inputText.length()];

I copied the contents of the file and passed it in as a normal String like so;

    String plain = "The text from the file"
    int key = 5;
    int offset = 3;
    String encrypted = rf.encrypt(plain, key, offset);
    System.out.println(encrypted);
    String unencrypted = rf.decrypt(encrypted, key, offset);
    System.out.println(unencrypted);

And it worked fine. But

    String plain = fh.inputReader();

Does not.

So inputReader() seems to work, the methods it's being passed into work, but I'm clearly missing something.

A nod in the right direction would be greatly appreciated, thanks friends.


Solution

  • Your result is stored in a local variable "inputText" and you are returning instance level variable which is null and is never reassigned. Remove String type as below and it should work:

    while ((line = br.readLine()) != null) {
            sb.append(line);
            inputText = sb.toString();
            //System.out.println(inputText);
        }