2012年05月06日 10:43供稿中心:兆隆教育
1.byte[]的长度
写了一个从文件里读字符串的函数:
public static String readFile(String fFileName){//, String fEncoding) {
char[] buffer = new char[1024];
StringBuilder text = new StringBuilder();
InputStreamReader reader = null;
try {
reader = new InputStreamReader(new FileInputStream(fFileName));
while (reader.read(buffer, 0, 1024)!=-1){
text.append(buffer); <==有错
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return text.toString();
}
粗看这段代码没有问题。但是读出的字符总比实际要多。问题在text.append(buffer)。 buffer是一个1024的char数组。每次append固定的1024个char.改成就好了。
reader = new InputStreamReader(new FileInputStream(fFileName));
int readed;
while ((readed = reader.read(buffer, 0, 1024))!=-1){
text.append(new String(buffer, 0, readed));
}
2.优先级的错误
Log.d(TAG, "location="+where+", "+locationService==null?"null":locationService.getLocation());
这行代码的本意是如果locationService==null,就输出"null",避免NullPointerException.但实际上仍然发生NullPointerException.原来"+"的优先级大于"?",所以上面代码实际上是:
Log.d(TAG, ("location="+where+", "+locationService)==null?"null":locationService.getLocation())
括号里的当然不会是null.改成
Log.d(TAG, "location="+where+", "+(locationService==null?"null":locationService.getLocation()));
就好了。
关键字:java软件工程师培训 兆隆IT云学院