Search code examples
javaandroidfilefileinputstreamlast-modified

Want the file date but can only use FileInputStream


I'm coding on an app, and have managed to read and write to text file with code like this:

    StringBuffer stringBuffer = new StringBuffer();
    try{
        FileInputStream fileInputStream = ctx.openFileInput(fileName);
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

        String lines;
        int counter = 0;
        while((lines = bufferedReader.readLine())!=null){
            if(counter>0){
                stringBuffer.append("\n");
            }
            stringBuffer.append(lines);
            counter++;
        }
    }
    catch (FileNotFoundException ex){
        throw ex;
    }
    catch (IOException ex){
        ex.printStackTrace();
        return null;
    }

But I also want to get the (last modified) date of the file.

I found codes like this:

    File file = new File(fileName);
    String path = file.getAbsolutePath();

    Date lastModDate = new Date(file.lastModified());

I tried this, using the same string for fileName, but it doesn't become e file. When doing

file.exists(); // = false

For a fileName I use just the file name, no path. I did the reading/writing in the simplest possible way, and want to keep it like that...

Is there a path missing for the FILE? Can I get the path from the FileInputStream in such case?

Greetings


Solution

  • Use:

    File file = new File(ctx.getFilesDir(), fileName);