我想创建一个能够从uri打开文本文件的应用程序。那时,我有这段代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_view_layout);
final Uri uri = getIntent() != null ? getIntent().getData() : null;
StringBuilder text = new StringBuilder();
InputStream inputStream = null;
}
如何让它读取整个文件? 最好的问候,Traabefi
答案 0 :(得分:3)
从File
的路径创建一个新的Uri
对象,并将其传递给FileInputStream
构造函数:
try {
inputStream = new FileInputStream(new File(uri.getPath()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Scanner s = new Scanner(inputStream).useDelimiter("\\A");
yourTextView.setText(s.hasNext() ? s.next() : "");
我从帕维尔·列宾的this回答中获得了InputStream
到String
技术。
别忘了关闭你的小溪。
答案 1 :(得分:2)
我已经做了一些魔术并且它的工作非常好:D这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_view_layout);
final Uri uri = getIntent() != null ? getIntent().getData() : null;
InputStream inputStream = null;
String str = "";
StringBuffer buf = new StringBuffer();
TextView txt = (TextView)findViewById(R.id.textView);
try {
inputStream = getContentResolver().openInputStream(uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
if (inputStream!=null){
try {
while((str = reader.readLine())!=null){
buf.append(str+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
txt.setText(buf.toString());
}
}