【问题标题】:Read and write a file with file chooser Android使用文件选择器 Android 读写文件
【发布时间】:2021-03-24 16:14:25
【问题描述】:

我正在使用 Android Studio 编写一个应用程序,我设置了一个文件选择器,它可以为我提供文件的路径(文件可以在外部或内部存储上)。我需要读取选择的文件,修改它并用另一个名称写在相同的位置。我已经实现了读写功能,但它们不适用于分隔符,因为它们使用 FileInputStream/FileOutputStream,我已经尝试过使用 FileReader 的函数但返回 null。有人如何解决我的问题? 提前致谢!

我的读/写功能:

public String Read_file(String fn, Context context) {
    int ch;
    String d;
    StringBuffer fileContent = new StringBuffer("");
    FileInputStream fis;
    try {
        fis = context.openFileInput(fn);
        try {
            while( (ch = fis.read()) != -1)
                fileContent.append((char)ch);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.out.println("Error");
    }
    return d = new String(fileContent);
}


public void Write_file(String fn, String data, Context context){
    FileOutputStream outS;
    //Scrive sul file
    try {
        outS = context.openFileOutput(fn, Context.MODE_PRIVATE);
        outS.write(data.getBytes());
        outS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我已经尝试过了,但返回 null:

public String t(String fname){

    BufferedReader br = null;
    String response = null;

    try {
        StringBuffer output = new StringBuffer();
        //String fpath = "/sdcard/"+fname+".txt";

        br = new BufferedReader(new FileReader(fname));
        String line = "";
        while ((line = br.readLine()) != null) {
            output.append(line +"n");
        }
        response = output.toString();

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
    return response;
}

我选择的文件:

protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == 10){
        if(resultCode == RESULT_OK){
            Uri uri = data.getData();
            String src = uri.getPath();
            String file_name = uri.getLastPathSegment();
            String fn = src.substring(src.lastIndexOf('/') + 1);
            System.out.println(fn);
            //////READ THE FILE AT THE URI
        }
    }
}

【问题讨论】:

  • “我已经设置了一个文件选择器,它可以为我提供文件的路径(文件可以在外部或内部存储上)”——这究竟是什么意思?您的代码可以读取和写入来自 Android SDK 称为 internal storage 的文件,但不适用于 external storageremovable storage
  • 使用文件选择器我可以选择一个文件并返回路径(例如下载文件夹或 sd 卡上),但我需要读取和写入该文件
  • “使用文件选择器,我可以选择一个文件并将路径返回给我”——请编辑您的问题并显示您使用此“文件选择器”的代码。例如,如果您的意思是ACTION_GET_CONTENTACTION_OPEN_DOCUMENT,它们都不是“文件”选择器,并且您都无法获得有用的“路径”。因此,虽然ACTION_GET_CONTENTACTION_OPEN_DOCUMENT 是正确的解决方案,但您需要使用Uri 值,使用ContentResolveropenInputStream()openOutputStream() 等方法。
  • 是的,抱歉,我已经用我的文件选择器进行了编辑

标签: java android file read-write


【解决方案1】:

在使用 fileName.getPath() 打开文件时遇到了类似的问题 一直找不到文件,并且所有内容:路径信息都丢失了。 查看内容提供商突出显示的 FileDescriptors。 打开 fileDescriptor 会生成 ParcelFileDescriptor,您可以在其中获取 fileDescriptor,然后根据您的用例打开 FileReader 或 FileInputStream。

fun readFile(fileName: Uri): String? {
    val fileDescriptor = requireContext().contentResolver.openFileDescriptor(fileName, "r") ?: return null
    val fReader = FileReader(fileDescriptor.fileDescriptor)

    //val file = File(fileName.path)
    var bufferedReader: BufferedReader? = null
    try {
        bufferedReader = BufferedReader(fReader)
        val stringBuilder = StringBuilder()
        var line: String?
        while (bufferedReader.readLine().also { line = it } != null) {
            stringBuilder.append(line)
            stringBuilder.append(System.lineSeparator())
        }
        return stringBuilder.toString()
    } catch (e: FileNotFoundException) {
        System.err.println("File :  Not found")
        e.printStackTrace()
    } catch (e: IOException) {
        e.printStackTrace()
    } finally {
        try {
            bufferedReader?.close()
            fReader.close()
            fileDescriptor.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    return null
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多