我刚来这地方。我认为自己已经打破了新手主义,我正在进入中级编程。我正在尝试从我的资产文件夹中读取,我遇到的问题是我的程序不断捕获异常。你能帮我弄清楚我做错了什么吗?这是我的代码:
package com.example.testone;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.widget.TextView;
public class AssetsTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
setContentView(textView);
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = getAssets().open("myawesometext.txt");
String text = loadTextFile(inputStream);
textView.setText(text);
} catch (IOException e) {
textView.setText("Couldn't load file");
} finally {
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e) {
textView.setText("Couldn't close file");
}
}
}
public String loadTextFile(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int len = 0;
while ((len = inputStream.read(bytes)) > 0)
byteStream.write(bytes, 0, len);
return new String(byteStream.toByteArray(), "UTF8");
}
}
我搜索了包括这个网站在内的每个网站,梳理了其他类似的问题,但找不到适合我的答案。非常感谢您的帮助。
提前致谢!