文件到字符串空指针异常

File to String Null Pointer Exception

我试图将文件内容作为字符串传递到方法中,但遇到空指针异常。我正在将文件转换为字符串,如下所示:

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;
    }
}

就将文件转换为字符串而言,这对我来说工作正常,但是当我尝试将其输出传递给另一个方法时,我在这里遇到空指针异常:

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

我复制了文件的内容,并像这样将其作为普通字符串传入;

    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);

而且效果很好。但是

    String plain = fh.inputReader();

没有。

所以 inputReader() 似乎有效,传递给它的方法有效,但我显然遗漏了一些东西。

不胜感激,谢谢朋友们。

您的结果存储在局部变量“inputText”中,您返回的实例级变量为 null,并且永远不会重新分配。如下删除字符串类型,它应该可以工作:

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