Michael
Michael

Reputation: 1030

List files written by OutputStreamWriter in Android

I'm creating some text files and save them with a timestamp in the method below:

private void writeToFile(String data) {
    try {
        Long tsLong = System.currentTimeMillis() / 1000;
        String fileName = tsLong.toString() + "ds.txt";

        Log.i("FILENAME", fileName);

        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE));
        outputStreamWriter.write(data + "\r\n");
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("FAILED", "File write failed: " + e.toString());
    }
}

Now in order to read from the files, I need the filenames. Is there any way to generate a list of all the files in that repository?

Upvotes: 0

Views: 233

Answers (2)

Omar HossamEldin
Omar HossamEldin

Reputation: 3111

If you mean with repository a folder on Android device then you need this snippet of code

File path = new File(mCurrentPath);
File[] dirs = path.listFiles();
List<String> files = new ArrayList<String>();
if (dirs != null) {
    Arrays.sort(dirs);
    for (File fentry : dirs) {
        if (!fentry.isDirectory()) {
            files.add(fentry.getName());
        }
    }
}

Upvotes: 1

ZeusNet
ZeusNet

Reputation: 720

As njzk2 mentioned you can get the dir where the files are saved via the getFilesDir() method.

Example code:

for(File file : getFilesDir().listFiles()){
    // Open file and read the content
}

Upvotes: 1

Related Questions