Android 将文件读取到字符串后,该字符串仍然为空
我有一个字符串对象s。我使用一个Android 将文件读取到字符串后,该字符串仍然为空,android,string,bufferedreader,Android,String,Bufferedreader,我有一个字符串对象s。我使用一个bufferedReader.readline()来写入它。我已经注销了s的内容,在logcat中我可以看到它们,所以我知道它不是空的。后来我使用s并调用它的String.split,但是我得到了一个NPE,为什么,当它已经填充了,所以不是空的 谢谢 String cachePath = getCacheDir().getAbsolutePath(); FileReader fr = null; try {
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));
}
String cachePath=getCacheDir().getAbsolutePath();
FileReader fr=null;
试一试{
fr=新文件读取器(cachePath+“/dbcache/”+“cacheTextFile.txt”);
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
BufferedReader br=新的BufferedReader(fr);
字符串s=null;
试一试{
而((s=br.readLine())!=null){
Log.e(标签“s=”+s);
}
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
试一试{
fr.close();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
HashMap hash=新的HashMap();
Log.e(标记“即将调用s”+s.length());
字符串[]arr=s.split(“,”);
对于(int i=0;i在中,当时,您总是覆盖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");
在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)在这里,当您到达末尾时,execue readLine它将返回null,因此s将为空,然后您将退出while循环抱歉,我没有跟上。为什么s仍然为null?当到达末尾时,这里((s=br.readLine())!=null),并且execue readLine它将返回null,因此s将为null,然后退出while循环