我想读取一个输入流,我的问题是这个方法总是返回null,虽然没有Exception输出和String输出(见下文)是正确的.. 有没有人知道如何解决这个问题?
private ArrayList<String> getPlayer(String name){
try{
byte[] b = new byte[1024];
int numBytes;
InputStream in = openFileInput(name);
ArrayList<String> content = new ArrayList<String>();
while((numBytes = in.read(b)) != 0){
content.add(new String(b, 0, numBytes, "UTF-8"));
String string = new String(b, 0, numBytes, "UTF-8");
System.out.println(string); //StringOutput
}
return content;
}catch(Exception e){
System.out.print(e.getMessage()); //ExceptionOutput
return null;
}
}
Exception,抛出并使应用程序停止:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: auldo.trainersoccer, PID: 7733
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at auldo.trainersoccer.ManageSpielerActivity$1.onItemClick(ManageSpielerActivity.java:60)
at android.widget.AdapterView.performItemClick(AdapterView.java:310)
at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066)
at android.widget.AbsListView$3.run(AbsListView.java:3903)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
答案 0 :(得分:3)
您的while循环条件存在问题
while((numBytes = in.read(b)) != 0){
将其更改为:
while((numBytes = in.read(b)) > 0){
当您使用!=
条件时会发生StringIndexOutOfBoundsException,因为当您到达文件末尾时,in.read
方法会返回 -1
答案 1 :(得分:1)
由于 StringIndexOutOfRangeException 而发生错误。
您没有检查是否已到达流的末尾。正如Java doc所述,流的结尾由返回值 -1 表示。所以你应该做((numBytes = in.read(b) != -1)
。