Is this correct way of checking if file exists - android

I am trying to create a file on the internal storage. If the file exists then I will just append to it, otherwise I will create it and put header into it.
I did it by calling openFileInput and if exception is thrown then the file does not exists and I set it up. If no exception then I will open the file to append to it
Here is the code, Is it Okay? I feel there is so much redundnacy
try{
openFileInput(filename);
FileoutputStream fos = OpenFileOutput(filename,Context.MODE_PRIVATE);
}catch(FileNotFoundException e){
setupFile(filename);
}

You could try something like:
File file = new File(path);
if(file.exists()){
//do stuff
}

You could try the following:
public Boolean fileExists() {
File myFile = new File(PATH);
return myFile.exists();
}
Within the file constructor goes the full path to the file plus the file name that you are checking for.
This will return a Boolean value that you can then use for determining what to do in the case of true/false.

This is what I use:
try {
file = openFileInput(filename);
} catch (FileNotFoundException e) {
// file does not exist
return false;
}

Related

How do I change FileOutputStream directory when saving a file in Android?

Here's my code:
String content = mEditText.getText().toString();
FileOutputStream fos;
try {
fos = openFileOutput(title, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(EditActivity.this, "Saved to "+getFilesDir() + "/" + title, Toast.LENGTH_LONG).show();
fos.close();
saved = true;
} catch (IOException e) {
Toast.makeText(EditActivity.this, "Error happened", Toast.LENGTH_SHORT).show();
}
If I run the code like this, it tells saved to /data/data/mypackagename/files/FileTitle. I want it to save the file in another directory for example save to /data/data/mypackagename/files/userData/FileTitle.I don't know any way to do this
What you need is the File constuctor that takes a parent File and a relative path to file. You've correctly established that openFileOutput() creates the file in getFilesDir(), so the code would look something like this:
FileOutputStream fos = null;
try {
final File dir = new File(getFilesDir(), "some/long/path");
dir.mkdirs();
final File file = new File(dir, "file.txt");
fos = new FileOutputStream(file);
// Use fos...
} catch (IOException e) {
// Handle error...
} finally {
if (fos != null) {
try {
fos.close()
} catch (IOException ignore) {
// Close quietly.
}
}
}
File is just a pointer, it may point to a directory, it may even point to something that's not there yet, like a new file. FileOutputStream will create a file if it doesn't exist.
If you choose to place your new file in another directory, make sure it exists first by calling mkdirs() on the directory.

How to delete a file from internal memory before replacing it

I would like to delete an internal file at runtime. When I download from an external server, the old version of the file (with the same name) is replaced, however I am unable to read it. I think that I need to delete the previous file before downloading the new version. Here is an example of what I have tried so far:
try {
FileOutputStream fos = getApplicationContext().openFileOutput("mytext.txt", Context.MODE_PRIVATE);
fos.write(getStringFromFile(pictosFile.getAbsolutePath()).getBytes());
Log.e("mytextfile",""+getStringFromFile(pictosFile.getAbsolutePath()));
progressDialog.cancel();
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
This allows me to save the file into internal memory, but I am unsure about how to delete the previous file before writing the new version.
If you need to ensure that the file is overwritten, i.e. delete an old copy before saving a new version, you can use the exists() method for a file object. Here is an example showing how to delete an old version of an image file before writing a new file with the same name in a nested directory:
// Here TARGET_BASE_PATH is the path to the base folder
// where the file is to be stored
// 1 - Check that the file exists and delete if it does
File myDir = new File(TARGET_BASE_PATH);
// Create the nested directory structure if it does not exist (first write)
if(!myDir.exists())
myDir.mkdirs();
String fname = "my_new_image.jpg";
File file = new File(myDir,fname);
// Delete the previous versions of the file if it exists
if(file.exists())
file.delete();
String filename = file.toString();
BufferedOutputStream bos = null;
// 2 - Write the new version of the file to the same location
try{
bos = new BufferedOutputStream(new FileOutputStream(filename));
Bitmap bmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
bmp.copyPixelsFromBuffer(buf);
bmp.compress(Bitmap.CompressFormat.PNG,90,bos);
bmp.recycle();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
finally{
try{
if(bos != null)
bos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
You must also ensure that you have read / write access to memory, make sure that you ask the user for these permissions at run time and have the following in your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Android: File Not Found Exception

I am trying to program a simple todo app for my android phone. Ive gotten far enough that I would like to save these strings that I input. However, every time I try to write the data I get a file not found exception. Here is the code I use in my onCreate method to instantiate the File.
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
I then have two methods, one to write to the File, and the other to read from it. They look like this:`
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader("Todo_File.txt"));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
and
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("Todo_File.txt"));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
items is a stringArray which holds the strings that were input. Every time that I try to write or read the files I get the following exception:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
I don't understand why Android Studio cant find the file that I created, can anyone help?
You are looking for a file "Todo_File.txt".
Where have you kept this file?
Are you keeping it as a resource file in the "res/raw" directory of your app or it is lying somewhere in the phone storage?
Here you can get some idea of types of the storage
https://developer.android.com/guide/topics/data/data-storage.html
https://android.stackexchange.com/questions/112951/two-types-of-internal-storage-what-is-the-difference
Mostly likely I guess you need to correct the path of this file.
here are the way to get the "/storage/sdcard0/" path
Environment.getExternalStorageDirectory()
The standard way to do File-IO in Android is using the context-relevant IO-methods.
To write a file, use the following code. Details about the different file-modes are available here.
FileOutputStream fOut = openFileOutput("Todo_File.txt", MODE_WORLD_READABLE);
To read a file, use this:
FileInputStream fIn = openFileInput("Todo_File.txt");
Since you defined
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
you can do:
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader(itemFile));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(itemFile));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
You need to actually create the file before you write to it. You should do something like this:
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
What you have done is simply tried to read from the file. The fact that you get the error:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
Is an indication that the file you want to write to hasn't been created, and I don't see you creating the file anywhere.
If you are using an emulator, you need to make sure that you have an SDK card set up on your device, and then do:
File itemFile = new File(Environment.getExternalStorageDirectory(),"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}

Read/Write file in android

try {
PrintStream out = new PrintStream(openFileOutput("OutputFile.txt", MODE_PRIVATE));
str=mIn.getText().toString();
out.println(str);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
i want to ask if this code create file called(OutputFile)?and if yes where is the path of this file??
i want to ask if this code create file called(OutputFile)
it creates a file called OutputFile.txt
and if yes where is the path of this file??
you can retrieve its path using getFileStreamPath, which returns the file created with openFileOutput
File file = getFileStreamPath("OutputFile.txt");
String path = null;
if (file != null) {
path = file.getPath();
}

Issue on appending a file in android

I am creating an android application which reads and writes data to a file in the location /sdcard/ReadandWrite/.when i writing to that file it does not write in append mode.it will removes the old data and writes the new one.please help me to solve this.Here is my code.
private File openfile() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
dir.mkdirs();
File file = new File(dir, "myfile.txt");
file.setWritable(true);
if(file.exists())
{
file.canRead();
file.setWritable(true);
}
else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private void writetofile() {
try {
File file=openfile();
OutputStreamWriter myOutWriter =
new OutputStreamWriter(new FileOutputStream(file));
myOutWriter.append(text.getText());
myOutWriter.close();
myOutWriter.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
You need to configure the FileOutputStream to use append mode. From JDK documentation:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified
name. If the second argument is true, then bytes will be written to
the end of the file rather than the beginning. A new FileDescriptor
object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called
with name as its argument.
If the file exists but is a directory rather than a regular file, does
not exist but cannot be created, or cannot be opened for any other
reason then a FileNotFoundException is thrown.
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or
cannot be opened for any other reason.
SecurityException - if a security manager exists and its checkWrite method denies write access to the file. Since:
JDK1.1 See Also:
SecurityManager.checkWrite(java.lang.String)
So change
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));
to
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));

Categories

Resources