I want to know if a file exists. I have created it and stored with sharedPreferences, but Android doesn´t get me the true route.
public class SplashScreen extends AppCompatActivity
{
super.onCreate(SavedInstanceState);
setContentView(R.layout.activity_splash_screen);
String FILE_NAME = "configAjustes.xml";
new Handler().postDelayed(() -> {
File file1 = new File(getApplicationContext().getFilesDir().getPath(),FILE_NAME);
Log.d("fc","file1 is "+file1);
Log.d("fc","file1 name is "+file1.getName);
if(file1.exists())
{
Log.d("fc","exists");
Intent inMain = new Intent (getApplicationContext(),MainActivity.class);
startActivity(inMain);
finish();
}else
{
Log.d("fc","not exists");
Intent inSettings= new Intent(getApplicationContext(),Settings.class);
startActivity(inSettings);
finish();
}
},2000);
}
I get the following:
the problem is that the path that android gives me is not true, because the xml file is not in "files". It is in "shared_prefs"
How can I get the true path where my file is?
Normally, we do not think of SharedPreferences as a file, and there is no direct and reliable way to access them as a file.
The closest solution is:
File prefsDir = new File(getApplicationInfo().dataDir,"shared_prefs");
File file1 = new File(prefsDir, FILE_NAME);
Or possibly:
File dataDir = getFilesDir().getParentFile();
File prefsDir = new File(dataDir,"shared_prefs");
File file1 = new File(prefsDir, FILE_NAME);
However, there is no guarantee that these will work across all Android OS versions and all devices.
Related
i was using GetExternalStoragePublicDirectory but is deprecated now, it gets back the standard path "/storage/emulated/0/Download" but from Android 12 i can save, load only the file stored from my app, if i add the same file renamed by pc is "filtered" and not accessible, it looks like not present!
i store a txt file from my app, how can i work around to access again to download external public folder?
I have create a sample to test the GetExternalStoragePublicDirectory method and create a txt file in the Download folder. Here is the MainActivity's code:
Button write = this.FindViewById<Button>(Resource.Id.buttonwrite);
Button read = this.FindViewById<Button>(Resource.Id.buttonread);
write.Click += (s, e) =>
{
var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
var file = Path.Combine(path + "/app.txt");
using (System.IO.FileStream os = new System.IO.FileStream(file, System.IO.FileMode.OpenOrCreate))
{
string temp = "this is test string";
byte[] buffer = Encoding.UTF8.GetBytes(temp);
os.Write(buffer, 0, buffer.Length);
}
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
StartActivity(intent);
// this line code can open the download folder and view all the files in it. When the user click the file, it will be open
};
read.Click += (s, e) =>
{
var path = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads);
var file = Path.Combine(path + "/app.txt");
/* using (System.IO.FileStream os = new System.IO.FileStream(file, System.IO.FileMode.OpenOrCreate))
{
StreamReader streamReader = new StreamReader(os);
var content = streamReader.ReadToEnd();
} */
Intent intent = new Intent(Intent.ActionOpenDocument);
intent.AddCategory(Intent.CategoryOpenable);
intent.SetType("text/*");
intent.PutExtra(DocumentsContract.ExtraInitialUri, Uri.Parse(file));
StartActivityForResult(intent, 2);
//This code can open the file picker and let the user to choose a file
};
The app.txt file can still be read when I renamed as New.txt by the file manager. Just change var file = Path.Combine(path + "/app.txt"); to var file = Path.Combine(path + "/New.txt"); and use the code in the /* can read it. So if the file was created by your app, your app can access it even though the file has been renamed by the uesr. But you can access the file in the public folder which was not created by your app.
In addidion, if you don't have to push your app to the google play, you can use the access all file permission according to my old answer in this link and the answer about the deprecated GetExternalStoragePublicDirectory.
I am making an application in which I have to save video files internally(in app memory when app is uninstalled all the filed should also be uninstalled).For this I have read many articles and googled a lot and found different solutions and after that I made a method there I wrote the code for that here is the code
public static boolean checkIfAlreadyDownloaded(Context context, String rhymeName) {
ContextWrapper cw = new ContextWrapper(context);
File rhymeDirectory = cw.getDir(Constants.INTERNAL_DIRECTORY_NAME, Context.MODE_PRIVATE);
if (rhymeDirectory.exists()) {
File individualRhyme = new File(rhymeDirectory, rhymeName);
if (individualRhyme.exists())
return true;
}
return false;
}
Here Constants.INTERNAL_DIRECTORY NAME is "Rhymes"
what I understand is if there is no directory then it returns false but When I install my app first time it return true.Even I uninstalled it and then reinstall it is always returning true .My question is "why it is always returning true"? Shouldn't it return false first time?Correct me please if I am wrong.
ContextWrapper.getDir() creates the directory if necessary, as said in the documentation:
public File getDir (String name, int mode)
Retrieve, creating if needed, a new directory in which the application can place its own custom data files.
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
//Creating an internal dir;
File fileWithinMyDir = new File(mydir, "myfile");
//Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
//Use the stream as usual to write into the file
For deleting a file from internal :
if (new File("path/to/file").delete()) {
// Deleted
} else {
// Not deleted
}
I'm having a problem getting files from my Android application's cache folder. This is what I'm trying to to but doesn't work:
File cacheDir = getApplicationContext().getCacheDir();
myFile = File.createTempFile("filename", ".mp3", cacheDir);
...
// Here I have to code to initialize the file
...
Log.i(LOG_TAG, "file.length = "+myFile.length()); // This logs correct info
...
//File file = new File(myFile.getPath());
//Log.i(LOG_TAG, "file.length() = "+file.length()); // This logs 0
//Log.i(LOG_TAG, "file.name = "+file.getName()); // This is correct
String fileURI = myFile.getPath();
mediaPlayer.setDataSource(fileURI);
mediaPlayer.prepare(); // This crashes
As you can see it seems the file doesn't contain anything. However I've tried to swap the two first lines with this piece of code and then it works.
myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYFOLDER/filename.mp3");
I haven't found any way to set my mediaPlayer without the URI and when I try to get the file from the URI it seems to be a problem.
Do you have solution to how I can get the file from the cache directory?
Ok, I managed to find a solution to this myself. First, I was able to "add content" to the file by changing createTempFile with this:
myFile = new File(getFilesDir(), "filename.mp3");
Unfortunately, seems you can't read files from this directory. You can read more about this here.
Therefore I found this post and I managed to solve it. Here is my final code:
myFile = new File(getFilesDir(), "filename.mp3");
...
Button playBtn = (Button) findViewById(R.id.button_play);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play(myFile);
}
});
...
public void play(File f) {
try {
FileInputStream fis = new FileInputStream(f);
mediaPlayer.setDataSource(fis.getFD());
mediaPlayer.prepare();
mediaPlayer.start();
...
If you can't pass the file, then I can't help you. But please post solution when you find one.
I want to check if file exists in my package folder, but I don't want to create a new one.
File file = new File(filePath);
if(file.exists())
return true;
Does this code check without creating a new file?
Your chunk of code does not create a new one, it only checks if its already there and nothing else.
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.
File file = new File(filePath);
if(file.exists())
//do something
It worked for me:
File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
if(file.exists()){
//Do something
}
else{
//Nothing
}
When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().
Sample code (in an Activity):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}
The methods in the Path class are syntactic, meaning that they operate on the Path instance. But eventually you must access the file system to verify that a particular Path exists
File file = new File("FileName");
if(file.exists()){
System.out.println("file is already there");
}else{
System.out.println("Not find file ");
}
public boolean FileExists(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
if(new File("/sdcard/your_filename.txt").exists())){
// Your code goes here...
}
Kotlin Extension Properties
No file will be create when you make a File object, it is only an interface.
To make working with files easier, there is an existing .toFile function on Uri
You can also add an extension property on File and/or Uri, to simplify usage further.
val File?.exists get() = this?.exists() ?: false
val Uri?.exists get() = File(this.toString).exists()
Then just use uri.exists or file.exists to check.
imagedirectory = new File(path);
imagepool = imagedirectory.listFiles();
Uri targetdelete = Uri.fromFile(imagepool[photoindex]); //photoindex is integer 1
File filetodelete = new File(targetdelete);
boolean deleted = filetodelete.delete();
I am receiving an error in this line
File filetodelete = new File(targetdelete);
it says targetdelete must be a string object.... I thought it was valid to put Uri object as the agrument when initializing a File object?
Thanks once again, wonderful experts on stack overflow!!
Why not just do deleted = imagepool[photoindex].delete();