【问题标题】:String still null after reading file to it读取文件后字符串仍然为空
【发布时间】:2013-02-06 14:20:12
【问题描述】:

我有一个字符串对象。我使用bufferedReader.readline() 给它写信。我已经注销了 s 的内容,在 logcat 中我可以看到它们,所以我知道它不为空。我后来使用 s 并在其上调用 String.split,但我得到了一个 NPE,为什么,当它已经填充而不为 null 时?

谢谢。

String cachePath = getCacheDir().getAbsolutePath();
        FileReader fr = null;
        try {
            fr = new FileReader(cachePath + "/dbcache/" + "cacheTextFile.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(fr);
        String s = null;
        try {
            while((s = br.readLine()) != null) {
            Log.e(TAG, "s = " + s);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {

            fr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 



        HashMap<String, String> hash = new HashMap<String, String>();
        Log.e(TAG, "about to call on s"+s.length());
        String[] arr = s.split(",");

        for(int i = 0; i < arr.length; i=i+2){
            String key = arr[i].toString();
            hash.put(key, "-1");
            Log.e(TAG, "hash key = " + hash.get(key));
        }

【问题讨论】:

    标签: android string bufferedreader


    【解决方案1】:

    while 中,您总是覆盖s 字符串..所以当您到达末尾时,它将是null

     while((s = br.readLine()) != null) {
        Log.e(TAG, "s = " + s);
     }
    

    改为这样做..

     StringBuilder stringBuilder = new StringBuilder();
     String currentLine = null;
      while((currentLine = br.readLine()) != null)
            stringBuilder.append(currentLine + "\n");
    

    【讨论】:

    • 对不起,我没有关注。为什么 s 仍然为空?
    • while((s = br.readLine()) != null) 到最后,执行readLine返回null,所以s为null,然后退出while 循环
    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多