get file location in android? - android

I use the following code to check file availability
File f1=new File("/data/data/com.myfiledemo/files/settings.dat");
if(f1.exists())
textview.setText("File Exist");
If i use the following code it's not responding
File f1=new File("settings.dat");
if(f1.exists())
tv.setText("File Exist");
Here com.myfiledemo is my application package . I simply create the file like this
fileInputstream = openFileInput("settings.dat");
why It's not responding for the second if condition.??Is it Wrong??

The second code snippet is not the correct way to use, If you insist on using a java.io.File object, it should be:
File f1=new File(context.getFilesDir(), "settings.dat");
if(f1.exists()) {
tv.setText("File Exist");
}

If you create the file by using openFileInput, then this is the way to check whether the file exists or not:
FileInputStream input = null;
try{
input = openFileInput("settings.dat");
}
catch(FileNotFoundException e){
// the file does not exists
}
if( input != null ){
tv.setText("File Exist");
}

Related

Error while using Google Drive API when the specified file is already open in read only mode

mFileId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
Log.e("file id", mFileId.getResourceId() + "");
DriveFile file = mFileId.asDriveFile();
try {
results = file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).await();//this is to return a driveContent object
DriveContents contents = results.getDriveContents();
This is the error it gives when that file should be opened in readonly mode, but the file is already open in readonly mode
InputStream in=contents.getInputStream();
Try to use java.io.File.setReadOnly() to set a file to readonly. Also check whether the file has been created or exists first and then set the read only flag.
File file = new File("C:/path/file.txt");
if (file.exists()) {
file.setReadOnly();
} else {
System.out.println("File does not exists.");
}
Check these related threads and this example from the documentation:
how to set read only access for file using java
How can I create constrained InputStream to read only part of the file?

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.

Error when call write()

I have error in line:
workbook.write();
When I try debug, i see massage: "Source not found."
How it fix?
private void exportExcel() throws IOException, WriteException{
File file = new File(Environment.getExternalStorageDirectory() + "/backup.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
}
Thanks in advance
WTF my code above begin to work!!!
When I started, I using default jexcelapi. Afterwards I begin using alternative jexcelapi, but it also not work.
When I try your code with little changes - it work! Your code:
private void exportExcel() throws WriteException, IOException{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard + "/myFolder");
//make them in case they're not there
dir.mkdirs();
//create a standard java.io.File object for the Workbook to use
File wbfile = new File(dir, "backup.xls");
WritableWorkbook workbook = null;
try{
workbook = Workbook.createWorkbook(wbfile);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
} catch (IOException ex) {
Log.e("Workbook Test", "Could not create " + wbfile.getPath(), ex);
}
}
But when I try my code above, it also work.
Maybe Eclipse not instantly update using library?
Thank you very much!
P.S. Excuse me for my bad english.
Your code does not check that the external storage directory is actually available. You need to call getExternalStorageState and check the return value against the various MEDIA_* values defined in Environment. If the directory is not available, that may cause the problem.
The problem also may be that you are trying to write to the root of the external storage directory. From the docs:
Applications should not directly use this top-level directory, in order to avoid polluting the user's root namespace. Any files that are private to the application should be placed in a directory returned by Context.getExternalFilesDir, which the system will take care of deleting if the application is uninstalled.
EDIT
Try this code:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard + "/myFolder");
//make them in case they're not there
dir.mkdirs();
//create a standard java.io.File object for the Workbook to use
File wbfile = new File(dir, "backup.xls");
try{
WritableWorkbook workbook = Workbook.createWorkbook(wbfile);
workbook.createSheet("worksheet", 0);
workbook.write();
workbook.close();
} catch (IOException ex) {
Log.e("Workbook Test", "Could not create " + wbfile.getPath(), ex);
}
return wb;
That should tell you more about what's going on.
EDIT 2
After a little more research, I found another possible issue: JExcelApi uses a lot of resources when it is creating a file. One solution is to use a temp file. Add the following code:
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setUseTemporaryFileDuringWrite(true);
and inside the try block, change the line that creates the workbook:
WritableWorkbook workbook = Workbook.createWorkbook(wbfile, wbSettings);

Check if file exists on SD card on Android

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}

Android file.exists() not working

Hallo,
Here's some code which writes a data class to a file, then checks to see that the file exists. I can see that the file exists on the emulator, but file.exists() and therefore saveStateAvailable() returns false.
private void saveStateFile() {
/*DEBUG*/Log.d(this.getClass().getName(), "saveStateFile: Started");
mGameData = getGameData();
try {
FileOutputStream fileoutputstream = openFileOutput(mGameData.pilotName + STATE_FILE_EXTENSION, Context.MODE_WORLD_WRITEABLE);
ObjectOutputStream objectoutputstream;
objectoutputstream = new ObjectOutputStream(fileoutputstream);
objectoutputstream.writeObject(mGameData);
objectoutputstream.close();
fileoutputstream.close();
/*DEBUG*/Log.i(this.getClass().getName(), "saveStateFile: State saved to "+mGameData.pilotName + STATE_FILE_EXTENSION);
} catch (IOException e) {
/*DEBUG*/Log.e(this.getClass().getName(), "saveStateFile: Error writing data state file, "+mGameData.pilotName + STATE_FILE_EXTENSION);
e.printStackTrace();
}
/*DEBUG*/Log.d(this.getClass().getName(), "saveStateFile: Finished stateFileAvailable="+stateFileAvailable());
}
private boolean stateFileAvailable() {
File file = new File(mGameData.pilotName + STATE_FILE_EXTENSION);
/*DEBUG*/Log.d(this.getClass().getName(), "stateFileAvailable: Called ("+mGameData.pilotName + STATE_FILE_EXTENSION+" exists = "+file.exists()+")");
return file.exists();
}
Any ideas?
-Frink
You need to use Context#getFileStreamPath(String) where the String is the filename of the File object you are trying to access. Then you can call File#exists on that object. So:
File file = getFileStreamPath(mGameData.pilotName + STATE_FILE_EXTENSION);
Gives you access to the File object that points to the correct place in your private app storage area.
What your code is going atm is accessing the file /<your file name> which is on the root path. You file obviously does not exist there.

Categories

Resources