Reputation: 3638
I'm trying to read from a file in Android Studio, in a small Java app. So I'm trying this:
File test = new File("C:\\testing\\testFile.dat");
if (test.exists()) {
System.out.println("test exists");
}
else {
System.out.println("test doesn't exist");
}
The file definitely exists, but it keeps on reporting that the file doesn't exist. I was able to work around this with another file by using the AssetManager
and reading it through a stream, but the method I'm calling now requires a File
's absolute path, but it's point blank refusing to find the file.
Am I doing something dumb, or misunderstanding something?
UPDATE Ok, thanks for the input, I've now solved the problem. First I had to upload the file I wanted into the virtual device's storage, then I was able to get the path to it.
File test = new File(this.getFilesDir().getAbsolutePath(), "testFile.dat");
Upvotes: 0
Views: 3227
Reputation: 11018
You can place this file in your assets/
folder inside the android project and access using the following code.
val inputSteam = assets.open("testFile.dat")
or place it inside the res/raw
folder and access it like below.
val inputStream = resources.openRawResource(R.raw.testFile)
We can't access a file on a development machine like this and won't be available on an android device so it will break so it's better if we move this somewhere inside the project and access it as above.
Upvotes: 1
Reputation: 1006674
but the method I'm calling now requires a File's absolute path
Assets are files on your development machine. They are not files on the device.
Ideally, you switch to some library that supports InputStream
or similar options, rather than requiring a filesystem path. If that is not an option, you can always get the InputStream
from AssetManager
and use that to make a copy of the data in some file that you control (e.g., in getCacheDir()
). You can then pass the path to that file to this method.
Upvotes: 1