Android Studio cannot read from file, does not exist - java

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");

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.

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.

Related

Java FileNotFoundException when trying to read txt file from resources folder

I'm trying to read a text file located in src/main/resources/test/file.txt. I'm trying to get the path of the file using String path = getClass().getResource("/text/file.txt").getFile(); but when I try to read it I get a FileNotFoundException. I tried putting many different paths, all of which failed. How can I go about doing this?
The idea of putting something into the src/main/resources tree is that it will be copied into the JAR file that you build from your project. It will then be available to your application via the Class methods getResource(String) and getResourceAsStream(String) methods.
When you are running in your application in the development environment, it is certainly possible to use FileInputStream etcetera to access the resource. But this won't work in production. In production, the resources will then be inside your app's JAR file. FileInputStream cannot open a JAR file and its contents by name.
When you do this:
getClass().getResource("/text/file.txt");
you get a URL for the resource, which will look something like this:
jar:file:/path/to/your.jar!/text/file.txt"
It is not possible to turn that into a pathname the FileInputStream will understand. Whatever you try will give you a FileNotFoundException ... or something that is not the resource you want to read.
So what to do?
You have a few options, depending on your application's requirements.
You can use getResourceAsStream and use the resulting input stream directly.
You can copy the contents of getResourceAsStream to a temporary file, and then use the pathname of the temporary file.
You can create an application specific directory (e.g. in the user's home directory) and extract the file you need from the JAR into the directory. You might do this the first time the application runs.
You could open the JAR file as a JarFile and use that API to open an InputStream for the resource. But this assumes that that the resources are in a JAR ... and on some platforms (e.g. Windows) you may encounter problems with file locking. (And it would be a bad idea to attempt to update the resource in the JAR.)
Try giving complete path of the file from the disk.
C:\Users\MyUser\Desktop\file name with extension

Cannot write file to Documents folder

I'm trying to write to a file in Java, or create a new file if the file doesn't exist. (Using JDK 14). However, when I run the following code I get an IOException at the if statement condition that reads The system could not find the file specified if the file doesn't exist, and Access is denied if the file does.
File file = new File(filePath);
System.out.println(filePath); // C:\Users\username\Documents\test.txt
if (file.createNewFile()) {
System.out.println("File successfully created");
} else {
System.out.println("File already exists");
}
The code works when I attempt to save it to the desktop folder and saves the file successfully, but for whatever reason isn't allowed to touch Documents.
The user I'm running IntelliJ as has full access to all files on the computer, and running the IDE as administrator did not fix the problem. However, I can save to the user folder and the desktop. It is only Documents or child directories of it that I can't save to.
There are a few similar questions on the site such as this one, however the cause is not the same as in my case this is a permissions issue, and not an issue of a missing directory.
I've just hit this same issue. It seems that JFileChooser() on some Windows 10 installations doesn't tell the os that the user has selected a folder and as such Sandboxing, Malware Control, Access control blocks access to create a file even though the user had full access (permission checks are OK but file write fails with IOException 13 or Access Denied). However FileDialog() DOES work where JFileChooser fails...
Heres what I would do to try to debug this:
Should you be trying to save to 'My Documents' as opposed to 'Documents'?
Try to save the file to C:\Users\username\test.txt (I suspect that will work)
Try to save the file to C:\Users\username\My Documents\test.txt
If you really do want to save it to 'Documents' make sure the 'Documents' director exists.
If thats the case, open the properties on Documents under the security tab select Everyone under 'Group our user names' and 'Full control' under permissions. that will open it wide up and should allow file creation. you might want to take note of what the settings where so you can put them back as setting a directory to wide open permissions can be 'problematic'. try running the program again.
1
if you want write data to file just user any Writer For example:
FileWriter writer = new FileWriter(yourFile);
You can use stream filtering for faster action.
Show more your code. You've just showed condition for existing file.
2
if you want create file in Documents folder, get a path, then make a:
File file = new File(documentPath);
while(!file.exists())
file.createNewFile();
//condition for file existing...`
If I don't help, comment below, just I can't understand your question :). Good Luck

Get relative path to file within project in JNI

Using JNI I can't get access to files like this:
ifstream file("file.txt");
file.txt is in folder jni, which is the same folder as the native code files
I can only access absolute path ("/sdcard/file.txt"), but this trick is not what I'm looking for.
Tried "data/data/com.example.SomeExample/jni/file.txt" but no luck.
How should I refer to a file as reletive path when working in native code?
The jni folder is not added to your APK. If you want files to be bundled with your application, I'd suggest putting them in the assets folder. If the assets folder doesn't already exist, place it at the same level as the jni folder (so they are siblings).
If you take this approach you will have to use the Asset Manager. This has a native interface, found in android/asset_manager.h. To open your file use:
AAsset *a = AAssetManager_open(pAssetManager, "file.txt", AASSET_MODE_BUFFER);
if (a)
{
const void *res = AAsset_getBuffer(a);
//do something with the file!
AAsset_close(a);
}
There are different flags you can pass in instead of AASSET_MODE_BUFFER.

Android FileNotFound Exception with a plist file that will be built in

I am trying to open a file for an Android app I am making. I tested the code that opens this file on a regular Java project, and it opens fine. However when I use this code in an Android Java project I get an java.io.FileNotFoundException error.
File file = new File ("list.plist");
Now the list.plist file is in the parent directory of the project. This file will be included in the app as its the only one it will be using.
I guess I am used to Xcode where I can just place the file anywhere in the project and I can access it without a problem.
How am I supposed to structure this path?
Thanks :-)
I've used this but it also did not work.
File file = new File(context.getFilesDir().getAbsoluteFile(), "list.plist");
Firstly, you need to ensure the file you are using is packaged within your app - such as in the assets directory.
Secondly, Android automatically compresses plist files based on the extension. As a workaround, change the extension to something Android will not compress. These extensions include:
".jpg", ".jpeg", ".png", ".gif",
".wav", ".mp2", ".mp3", ".ogg", ".aac",
".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
".amr", ".awb", ".wma", ".wmv"
(for full article, see dealing-with-asset-compression-in-android-apps)
You need to put this file in the assets dir and not in the parent folder. Any files in the parent folder need not be packaged with the app. Moreover, the structure of your files on a phone is not the same as you see in eclipse.
You should use "res/raw" or "assets" directory to include a raw file in your Android project.
see: http://developer.android.com/guide/topics/data/data-storage.html
I added the list.plist to the assets folder and renamed it list.mp3 to avoid compression issues.
AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open("list.mp3");
This successfully opened the file without problems, which now allows me to parse the inputStream.
Thanks to Phil for giving sending me in the right direction.

Can't find folder or file created with Android App with windows file exlorer

I'm creating a directory and a text file on the sdcard in one of my apps because I want to be able to move it to my computer for analysis. But I can't find the folder or the file I'm creating on my sdcard using the file browser on my computer.
I CAN find and read the file using my phones file manager but not using the file browser in windows.
So the file and folder are succesfully created and I can write to the file, I can also find and read the file using the file manager on my phone but I can't find either directory or file using my computer.
I have a uses permission for the application to allow it to write to external storage.
This is the code I use to create the file and directory.
String fileName = "testFil.txt";
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/PulsApp";
File appDirectory = new File(path);
appDirectory.mkdirs();
File file = new File(path, fileName);
try {
file.createNewFile();
} catch (IOException e) {
}
Does anyone know what the problem is and how to fix it? I really need to be able to write files to my sdcard so I can transfer them to my computer.
I am completely baffled by this problem since all the research I've done point to that everyone else is doing the same thing.
If your device is running Android 3.0 or higher, you also need to use MediaScannerConnection to index your newly-created file before it will show up on a development PC's file explorer.
More accurately, the newly-created file needs to be indexed by the MediaStore. That will eventually happen for other reasons (e.g., device reboot). However, you are better served using scanFile() on MediaScannerConnection to get it to happen more quickly.
I blogged about this last summer.
Sometimes that the MediaScannerConnection will recognize the folder as a unknown type file, so try to create another folder inside the original one can avoid this problem.
I have met the same problem, and I use the method in the comment
And it works for me.

Categories