簡體   English   中英

文件到字符串 Null 指針異常

[英]File to String Null Pointer Exception

我正在嘗試將文件的內容作為字符串傳遞給方法並遇到 Null 指針異常。 我正在將文件轉換為這樣的字符串:

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

就將文件轉換為字符串而言,這對我來說很好,但是當我嘗試將 output 傳遞給另一種方法時,我在此處得到 null 指針異常:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM