在Intent.ACTION_GET_CONTENT之后读取Android打开的文本文件

mic*_*ael 2 storage android file internal

流程是:

  1. 用户需要选择要使用的文本文件和弹出的默认Android浏览器.
  2. 然后我想存储包含文件名的字符串,以实际打开文件进行读取.
  3. 我想打开该文件并将其重写为app内部存储上的新文件.
  4. 我想从app内部存储打开新创建的文件.
  5. 奖金1 - 如果它现在是.txt文件但是.doc,我想.txt在重写的上面的步骤3中将他转换为常规文件.
    奖金2 - 如何处理大型文本文件?

这是代码:

// 1. Start with user action pressing on button to select file
addButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        startActivityForResult(intent, PICKFILE_RESULT_CODE);          
    }
});

// 2. Come back here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICKFILE_RESULT_CODE) {
        // Get the Uri of the selected file
        Uri uri = data.getData();
        String filePathName = "WHAT TODO ?";
        LaterFunction(filePathName);
    }
}

// 3. Later here
public void LaterFunction(String filePathName) {
    BufferedReader br;
    FileOutputStream os;
    try {
        br = new BufferedReader(new FileReader("WHAT TODO ?"));
        //WHAT TODO ? Is this creates new file with 
        //the name NewFileName on internal app storage?
        os = openFileOutput("newFileName", Context.MODE_PRIVATE);                     
        String line = null;
        while ((line = br.readLine()) != null) {
            os.write(line.getBytes());
        }
        br.close();
        os.close();
        lastFunction("newFileName");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();     
    }
}

// 4. And in the end here
public void lastFunction(String newFileName) {
    //WHAT TODO? How to read line line the file 
    //now from internal app storage?
}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 6

第一步:删除 String filePathName = "WHAT TODO ?";

第2步:LaterFunction(filePathName);改为LaterFunction(uri);

第3步:br = new BufferedReader(new FileReader("WHAT TODO ?"));改为br = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri));

这是解决您问题的最低要求.

但是,MIME类型*/*将匹配任何类型的文件,而不仅仅是文本文件.不应使用复制二进制文件readLine().如果您只想要纯文本文件,请使用text/plain而不是*/*.