2

This is an android issue. A call to File.mkdirs can change the value of Context.getFilesDir. I've stated the problem this way since I haven't investigated all the test cases. I was very surprised by this result and put together a simple test that confirmed this behavior.

String filesDir = context.getFilesDir().getAbsolutePath();
File newFile = new File(context.getFilesDir,"xxx/MyFile.txt");
newFile.getParentFile().mkdirs();
String newFilesDir = context.getFilesDir().getAbsolutePath();

What you'll see is the filesDir and newFilesDir aren't the same. The call to mkdirs changed the location. I'm surprised by this result since the Android documentation doesn't mention this behavior. Anybody out there have a some valid explanation on why that's happening, and how to deal with that. I've been using getFilesDir as the place to store content and I like to organize that content in a directory tree and it looks like you shouldn't be adding directories in the filesDir.

Tom Rutchik
  • 1,183
  • 1
  • 12
  • 15
  • It is perfectly fine to create a subdirectory inside your application directory. Can you show more code pls? – user1506104 Jul 07 '19 at 06:14
  • I feel silly about this. I totally misread what I was seeing. In a debug session I looked at the value of context.getFilesDir() and expanded the second line which was a File. What I didn't realize was that was a file (actually the directory I had just added) contained in the getFilesDir(). Silly me for not recognizing that. It does however get me to think a little about the efficiency of File if every time you create one, you're also instantiating an File instance of every file/directory contained in it! – Tom Rutchik Jul 07 '19 at 18:39
  • 1
    I just looked at java source code for File. They're not instantiating an instance of every file contained in the File. So that means that the debug window is doing that as a friendly convenience. That's the only thing that makes sense. I was under the impression that when you view a object instance in the debugger window, you literally only saw what was contained in the object. Obviously some other convenience can be added for viewing/debugging an object instance on a per class basis. In the case of File, the debug view adds a convenience for navigating to the files it contains. – Tom Rutchik Jul 07 '19 at 19:55

1 Answers1

0

It is perfectly fine to create a subdirectory inside your application directory via getFilesDir() and mkdirs() commands. Know more here: https://developer.android.com/training/data-storage/files

user1506104
  • 6,554
  • 4
  • 71
  • 89