Android:读取所选文件并返回String的函数

时间:2017-02-01 14:56:23

标签: java android filechooser

我为Mac / Windows制作了一款应用。在这些操作系统上,我可以使用JFileChooser从我的计算机中选择一个文件。但是我要为Android制作我的应用的移动版本。这是我提到的功能代码,即桌面操作系统:

public static String readFile() {
    JFileChooser fc;
    File file;
    fc = new JFileChooser(defaultPath);
    if (fc.showOpenDialog(new JFrame()) == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile();
    } else {
        return null;
    }
    try {
        Scanner reader = new Scanner(file);
        content = reader.useDelimiter("\\A").next();
    } catch (IOException e) {
        System.exit(0);
    }
    return content;
}

我的问题是:如何让它在Android上运行?

1 个答案:

答案 0 :(得分:0)

如评论中所述,您无法使用一个功能完成所有操作。 以下是允许用户选择文件的几个库之一。 https://github.com/iPaulPro/aFileChooser 还有很多其他的。 获得文件的路径后,您可以使用此代码段(或类似的东西,您可以根据自己的需要调整它)来阅读它。

    String mResponse;
    File file = new File(*path*, *name*);
    try {
        FileInputStream is = new FileInputStream(file);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        mResponse = new String(buffer);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }