0

I made a app for Mac/Windows. On these OSes, I can use JFileChooser to choose a file from my computer. But I'm going to make a mobile version of my app, for Android. Here's my code of mentioned function, that is for a desktop OS:

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;
}

My question is: How to make it work on Android?

  • Since `JFileChooser` does not exist on Android, and since blocking UI (e.g., `showOpenDialog()`) does not exist on Android, and since you need to separate your UI work (on the main application thread) from your disk I/O (on a background thread), the Android equivalent of this will not be a single "function" and will not look much like what you have here. – CommonsWare Feb 01 '17 at 14:58
  • Is there any simple method to read a file on Android, without using a file chooser? – 화이트케이크 Feb 01 '17 at 15:03
  • That part would be no different than what you have in your `try`/`catch` block, though there are other ways of reading in content in Java besides using `Scanner`, and you would need to do that I/O work on a background thread (so you do not freeze your UI while the I/O is proceeding). – CommonsWare Feb 01 '17 at 15:16

1 Answers1

0

As stated in the comments, you cannot do it all with one function. Here is one of several libraries that allow the user to choose a file. https://github.com/iPaulPro/aFileChooser There are many others. Once you have the path of the file, you can read it for example with this snippet (or something similar that you can adapt for your needs)

    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;
    }
Beppi's
  • 2,089
  • 1
  • 21
  • 38