Android: Create a file from a Service - android

I have been successfully able to create files in my apps local directory using the below code
File appDir = new File(this.getExternalFilesDir(null), "my_folder");
if (!appDir.exists())
{
boolean result = appDir.mkdir();
if (!result) {
Log.i(Util.TAG, LOG_LABEL
+ ":: Unable to create \"my_folder\" Directory : "
+ appDir.getAbsolutePath()
+ " Directory already exists !");
}
}
File HTMLFile = new File(appDir,"html.txt");
But now when I tried to do the same from a service, the file was not being created, I even checked using 'HTMLFile.exists()' and it says the file does not exist.
My question is, Is it actually possible to create files from a service? or am I missing something here.

It is possible to write to the storage of your android: by the help of the following methods
Make sure you provide uses permission to write and read from storage in manifest file.
I have used this code:
private File newFile;
public ListenNotification() {
Log.d("Service","InConstrutor");
newFile=newFile(Environment.getExternalStorageDirectory(),"NotificationFromService");
if(!newFile.exists()){
Log.d("Service","Created");
newFile.mkdir();
}
else{
Log.d("Service","Existed");
}
}
File HTMLFile = new File(newFile,"html.txt");

Related

Want to create Folder in File Manager of App but couldn't

Folder is creating Successfully but the location is something like storage/emualted/0
I'm using Enviroment.getExternalStorageDirectory methods
I want to create publicily available folder which i could save my app's data what should i do?
use Context#getFilesDir() orContext#getCacheDir()
it was restricted from google. below android 7 only u can create a folder inside internal folder. after that u only can create folder inside downloads,music and alarm
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file = new File(folder, "example.txt");
if (!file .exists()){
file .mkdirs();
}else{
}
Finally it worked in Android 10
//by Using This Method
private void createFolder(String name) {
File mydir = getApplicationContext().getExternalFilesDir(name); //Creating an internal directory;
if (!mydir.exists()) {
mydir.mkdirs();
Toast.makeText(this, "Created" + " -> " + mydir.getAbsolutePath(), Toast.LENGTH_SHORT).show();
} else {
}

Android check existence of file in android internal storage

I put some .mp4 file in a folder in my android device internal storage. And then I play this file from my application. It plays well if exists otherwise app crushed.
So before play file I want to check its existence.
I tried below code but no luck.
File file = new File("file:///storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file exist");
} else {
LogUtil.printLogMessage(VideoListActivity.class.getName(), "video File", "file not exist");
}
i am sure the file is exist in the folder named tutorial in my internal storage.
Use file.isFile() for file & file.isDirectory() for directory,
file.exists() tries to access the file which causes it to crash if the file doesn't exist, file.isFile() uses linux stat, which only returns the information about the file without trying to access it.
Please make proper file name, Replace with File myDirectory = new File(Environment.getExternalStorageDirectory(), dirName);
public Boolean checkFile(){
File file = new File("/storage/emulated/0/tutorial/1a1cbfc4-18cb-4637-8405-01bf9bebeda3.mp4");
if (file.exists()) {
return true;
} else {
return false;
}
}
Use checkfile True/False flag before video play.
Try this
File file = new File(path);
if (!file.isFile()) {
}else{
}

Android - Missing files between file explorers

I'm trying to access the two files, Spring v2.json and Test.json, in my Android app. However, I will add them using Windows with my phone connected, but when I run my app, the file seems to disappear.
Getting the file
File file = new File(getExternalFilesDir(null), "Spring v2.json");
Check is the file exists
if (file.exists()) {
TransferObserver observer = transferUtility.download(
"easelbucket", // bucket to download from
"sections/" + objectKey, // key for object to be downloaded
file // file to download object to
);
} else {
Toast.makeText(this, "File does not exist", Toast.LENGTH_SHORT).show();
return null;
}
I know that the file stops existing because (1) the if statement enters the else block, and (2) the app crashes when it attempts to use the result of the file.
File file = new File(getExternalFilesDir(null), "/Spring v2.json")
You forget slash before filename.
Also check if
.canRead();
and
.canExecute();

Android; Check if file exists without creating a new 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.

Android How to use and create temporary folder

I develop an app which collects some data from internet. Then save it to a temporary folder. To build this app I need to create and access a folder ( just for the purpose of app, not for the user). How can I do it?
this code is to create folder:
File direct = new File(Environment.getExternalStorageDirectory() + "/New Folder");
if(!direct.exists())
{
(direct.mkdir()) //directory is created;
}
try it may help you
File mFile;
onCreate()
mFile= new File(Environment.getExternalStorageDirectory()+"/temp/";
mFile.mkdir();
onDestroy();
mFile.delete();
try out this...
private void makeFolder(){
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + getString(R.string.folder_name));
boolean mainfolderexist = root.exists();
if (!mainfolderexist) {
try {
if (Environment.getExternalStorageDirectory().canWrite()) {
root.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
All The best
You should really check this other SO answer: https://stackoverflow.com/a/6485850/65716
Aside from the fact that you have to completely manage your use of the space, etc, caching on external storage requires more permission for your app.
See http://developer.android.com/reference/android/content/Context.html#getCacheDir()
"Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage."
For app use only, I would recommend to use Context.getDir() for retrieving the directory if the files is used by our app only and don`t want to be visible to users by file browsers.
// No need to check if exist, created automatically.
File tempRoot = context.getDir("temp", Context.MODE_PRIVATE);
// do something

Categories

Resources