In C# there are Application.StartUpPath or Application.AppDataPath global methods to get a path where I would store Application Settings.
I tried static String fName = System.getProperty("user.dir") + "SatCli.conf";
"/SatCli.conf" - is the resulted fName
then I call
BufferedOutputStream oustream = new BufferedOutputStream(new
FileOutputStream(fName, false));
and I am getting the common exception
"/SatCli.conf: open failed: EROFS (Read-only file system)"
Well, I've been writing apps under Unix and I understand maybe the file name is refering to internal memory.. in other words to the root part of system file system.
Or maybe not.. maybe it refers to the App Folder?
Anyway, what I would like to get is the correct method to get the right folder to store the settings data.
Also, what is important, I need it before any context is built, when static fields are initializing.
Thank you for any relevant hint and help.
what I would like to get is the correct method to get the right folder to store the settings data.
For arbitrary files, call getFilesDir() on a Context (e.g., Activity). This gives you a File object representing a private directory where your app can read and write.
FWIW, Android's standard way of storing settings that you collect from the user is SharedPreferences, so you can take advantage of PreferenceFragment for the UI.
Related
i'm currently trying to develop a package for a Flutter App, with Kotlin. My issue is that I need to provide the package with a config file, which should only be defined inside the main App. Since the config differs for the Dev and Prod environment, the app should pass through the path of the File via the Method Channel. The problem is that the package isn't able to access the assets folder of the calling application.
Path: "assets/config.json" (the root being the main application)
Steps I already tried:
Creating the file inside the res/raw & accessing the config file through a ressource id -> Kotlin gives me an "Unresolved reference" error, unless I create the file inside the packages res/raw
Instead of passing through the path, I tried passing through the content of the config & writing it into an empty temporary file. The code in Kotlin like this:
val config = File(applicationContext.filesDir,"config.json")
config.writeText(configContent)
-> This works, but it seems like a weird solution to the problem.
please let me know if I need to provide further information & thank you in advance!
edit:
The Java Method that is called during initialisation:
public static void createMultipleAccountPublicClientApplication(#NonNull final Context context,
#NonNull final File configFile,
#NonNull final IMultipleAccountApplicationCreatedListener listener)
Flutter assets aren't files - they are packaged up and only available through the rootBundle. So, if you want to make a file from a text asset, someone has to load the asset and write it to a file.
As your plugin user will be in charge of the asset, they will have to do the first part (and will end up with a String). The question arises of who should do the writing.
You could make the plugin user use path_provider to find the temporary directory and write it there and then pass you the file path. Eventually, down in the Java, you new File(theTempFilePath). Or they could pass the string to the Dart half of your plugin and you create the temp file in the same way.
It's probably more convenient if they pass your plugin the string, you pass that to the native side and have the native side create a temporary file and write the string there. (BTW, I assume we are talking about this config file: https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-configuration#how-to-use-a-configuration-file )
See this answer for creating temporary files: Creating temporary files in Android
Note that there's actually no reason that your plugin user then needs to use an asset. They could, instead, just hard code the string in their code if the configuration never really changes.
There's an argument that as this is a JSON configuration file, you may not want to bother your user with the details of this JSON configuration file. You may want to default it in your Dart code (why not hard code it as a string, as above, if it never really changes) and then provide some methods to override particular values like the client id and the redirect uri, which may be the only things that users ever change in practice. So rather than making them supply a complete JSON file, they just give you those two strings and you plonk them into your default JSON. Maybe a version 2 feature :)
i need to make a compiler in android using the jflex and cup tools to read a file in the internal storage of the movile.
but the user need to input the path of the file and the user input its like:
/home/cp21.txt
but when i use the method openFileInput() it reads
/data/data/com.aplicattionpakagename/files/cp21.txt
and the file is in the buetooh directory of "Almacenamiento de telefono"
how can i read it?
Try using something in external storage with getExternalStorageDirectory().
If you want the user interface to expose that as /home, make sure you do a String replace between your view and model, s.t. /home is converted to /path/to/storage, and vice versa.
Using Eclipse, Android SDK.
I have a text file full of data that I need pulled in. (For now, it's the easier the way, eventually I'm going to need to scrape dynamic data from a URL, but for now I have the test data I need in this text file).
I've created a class to open this file, but no matter how I try to open it I keep geeting "file not found" exceptions.
I've tried putting my "data.txt" file in various relative paths (within my App):
- "/AppName/"
- "/AppName/src/com/example/appname/data.txt"
I've tried passing different relative paths. I've tried putting the text file in the same path of the .java class file that's trying to open it, and it still can't find it! What am I doing wrong?
What am I doing wrong?
You have two main options of where to store this file within your project directory: assets/ and res/raw/.
If you use assets/, you can call getAssets() on your Activity (or other Context), and on there call open() with the relative path within assets/ to get an InputStream on this file (e.g., assets/data.txt would be accessed via getAssets().open("data.txt")).
If you use res/raw/, you can call getResources() on your Activity (or other Context), and on there call openRawResource(), passing in the R.raw value based upon your filename (e.g., res/raw/data.txt would be accessed via getResources().openRawResource(R.raw.data)).
Use /res/raw directory. I read sound files from raw:
InputStream soundFile1 = context.getResources().openRawResource(soundOneId);
Where context is a base context of activity passed to the class.
http://developer.android.com/reference/android/content/Context.html
I want to create a file t save some information for my app next time initial use.
I want the file is place in program not in sd card.
What position of the file I can set?
InputStreamReader fsr = new InputStreamReader(openFileInput(**what position** +"test.xml"));
Context.getDir() also return private directory of your application.
Use openFileInput()/openFileOutput(), which can be called for any Context (including your Activity).
What's the best way to create a temporary file in Android?
Can File.createTempFile be used? The documentation is very vague about it.
In particular, it's not clear when temporary files created with File.createTempFile are deleted, if ever.
This is what I typically do:
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", ".extension", outputDir);
As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.
Best practices on internal and external temporary files:
Internal Cache
If you'd like to cache some data, rather than store it persistently,
you should use getCacheDir() to open a File that represents the
internal directory where your application should save temporary cache
files.
When the device is low on internal storage space, Android may delete
these cache files to recover space. However, you should not rely on
the system to clean up these files for you. You should always maintain
the cache files yourself and stay within a reasonable limit of space
consumed, such as 1MB. When the user uninstalls your application,
these files are removed.
External Cache
To open a File that represents the external storage directory where
you should save cache files, call getExternalCacheDir(). If the user
uninstalls your application, these files will be automatically
deleted.
Similar to ContextCompat.getExternalFilesDirs(), mentioned above,
you can also access a cache directory on a secondary external storage
(if available) by calling ContextCompat.getExternalCacheDirs().
Tip: To preserve file space and maintain your app's performance, it's
important that you carefully manage your cache files and remove those
that aren't needed anymore throughout your app's lifecycle.
For temporary internal files their are 2 options
1.
File file;
file = File.createTempFile(filename, null, this.getCacheDir());
2.
File file
file = new File(this.getCacheDir(), filename);
Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is .tmp by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp by default) e.g you specify your filename as internal_file and comes out as internal_file1456345.tmp. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates via file.getName();, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.
You can use the cache dir using context.getCacheDir().
File temp=File.createTempFile("prefix","suffix",context.getCacheDir());
You can use the File.deleteOnExit() method
https://developer.android.com/reference/java/io/File.html#deleteOnExit()
It is referenced here https://developer.android.com/reference/java/io/File.html#createTempFile(java.lang.String, java.lang.String, java.io.File)
Do it in simple. According to documentation
https://developer.android.com/training/data-storage/files
String imageName = "IMG_" + String.valueOf(System.currentTimeMillis()) +".jpg";
picFile = new File(ProfileActivity.this.getCacheDir(),imageName);
and delete it after usage
picFile.delete()