【问题标题】:File to String Null Pointer Exception文件到字符串空指针异常
【发布时间】:2020-07-14 16:06:27
【问题描述】:

我试图将文件的内容作为字符串传递到方法中并遇到空指针异常。我正在将文件转换为这样的字符串:

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() 似乎工作,它被传递到工作的方法,但我显然错过了一些东西。

非常感谢您向正确的方向点头,谢谢朋友。

【问题讨论】:

    标签: java arrays multidimensional-array tostring file-handling


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2017-10-24
      • 1970-01-01
      • 2016-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多