0

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

谢谢。

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

1 回答 1

3

在中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");
于 2013-02-06T14:23:54.220 回答