{Android} 我该如何通过uri打开我的文本文件?

4

我希望创建一个应用程序,能够从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

2个回答

6
我用一些技巧完成了这个任务,效果非常好: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());
    }
}

这就是答案。 - rommex

3

Uri 的路径创建一个新的 File 对象,并将其传递给 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() : "");

我从Pavel Repin的这个答案中学到了将InputStream转换为String的技巧。

记得关闭你的流。


然后我该如何将我的文件放入文本视图中?你能提供完整的代码吗? - Lukáš Anda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接