android create text file on install - java

I need help storing data on my Android app. I need to create a text file, but only once. I have tried if(file.exists()) and if (file!=null) but nothing's working.I need this text file to store user data strings between app restarts. This code will create the file onCreate everytime, but I need it to only do it if the file doesnt already exist
private void createFile(String filename){
if(memoryFile != null){
memoryFile = new File(getApplicationContext().getFilesDir(), filename);
}
}

This code will create the file onCreate everytime
No, it will not. It will not create any file. It creates an instance of a File object. That is a Java object that represents a (possible) file on the filesystem. It does not actually create the file. To create the file, write something to it, using a FileOutputStream (and a background thread). To see if the file already exists, call exists() on memoryFile.
Also, note that you do not need getApplicationContext() here. Just use getFilesDir().

Related

How to Get reference of Opened file in Java?

I want to build a method that opens an existing file and returns a reference to said file (Like a file handle) as an object. If I succeed in opening this file, then the fields of the file handle should be initialized with the information about the opened file, like for example the number of blocks stored in that file. Any Idea how to go about this? Any suggestions would be appreciated.
File fileReference = new File("/path/to/your/file");
if (fileReference.isFile()) {
long length = fileReference.length();
// etc.
}
See more available methods on the File class: https://docs.oracle.com/javase/7/docs/api/java/io/File.html

Reading specific String from text file using non-activity Java Class

I have a text file and it has -
packagename:com.hello
I have non-activity Java Class which has to read this text file fetch this com.hello and output it in the form of Log or Toast Message. I am doing Programming in Android in Eclipse. I have 2 questions..
1) Where do I need to place this text file I mean the location of it so that my JAva Class can read it.
2) Since my JAva Class is non-activity class, openFileInput is not working since it needs context and I have no way of getting context.
FileInputStream in = openFileInput("filename.txt");
Is there any way of doing it. Thanks in advance :)
1) Where do I need to place this text file I mean the location of it so that my JAva Class can read it.
Anywhere you want, just tell your app the correct path to the file.
2) Since my JAva Class is non-activity class, openFileInput is not working since it needs context and I have no way of getting context.
Just read the file in Java!!!
FileInputStream fis = new FileInputStream(new File("path/to/your/file.txt"));
NOTES:
you must throw or catch a FileNotFoundException
remember closing the stream when finished!!
1)You can place it anywhere inside your package ; just ensure you provide the correct path. 2)Refer this : How can I read a text file in Android?

Android get file using path (in String format)

My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:
File fileToSave = new File(dirOfTheFile);
Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?
That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.
The new keyword is creating a File object in code, not necessarily a new file on the device.
I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.
The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.
try this..
File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
// the file exists. use it
} else {
// create file here
}
if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders

rewrite file instead of recreating a file

I have the following piece of code which allows me to recreate a file holding updated data. Even though I used the "StandardOpenOption.TRUNCATE_EXISTING" option to overwrite the old file I was getting an error saying that the file already exists and it wouldn't write on top of it!
File filename = new File("data.txt");
public void writeToFile(char[] data){
filename.delete();
Files.write(filename.toPath(), data, StandardOpenOption.TRUNCATE_EXISTING);
}
Is it possible instead of deleting and recreating the same file over and over to edit the initial file's data?
Thank you
EDIT1: It seems like it was a mistake of mine. Together with "StandardOpenOption.TRUNCATE_EXISTING" I have included "StandardOpenOption.CREEATE_NEW".
This is because I want the file to be created in case it doesn't already exist! How is it possible to first try to edit it and if it doesnt exist create a new one?
Sorry for my initial mistake
The way to go on this one (which worked for me) is creating a try{}catch{} block and within the "try" try to edit the file and if it fails because it doesn't exist create a new file in the "catch".
Look at the JavaDoc of the write method in the Files class, it says: "By default the method creates a new file or overwrites an existing file", so it seems that all you need to do is:
File filename = new File("data.txt");
public void writeToFile(char[] data) throws IOException {
Files.write(filename.toPath(), data);
}

Why does my file.exists() always return false?

I store a photo taken by the camera like so:
FileOutputStream out = new FileOutputStream("img_example");
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
In the onCreate() method (of the same activity/file) I check if the file exists but I must be doing something wrong because it doesn't go inside the following test:
file = getApplicationContext().getFileStreamPath("img_example");
if(file.exists())
{
//doesn't go in here
}
I suspect it's something to do with the path or the context I've given.
Background Info:
I actually have 3 different instances of the above code. Inside the file.exists() test I display a tick next to the "take image" button. Eventually, I'll want to retrieve the image in another activity but for now I just want to check if it exists
The most obvious reason is "because it isn't there".
I note that your code is creating the file in the "current directory", and looking for the file in the application context. Apparently they are not the same place. Why not just ...
FileOutputStream out = new FileOutputStream(
getApplicationContext().getFileStreamPath("img_example"));
As it says in the android documentation:
getFileStreamPath(String name)
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
Why not write your file using the openFileOutput() method?

Categories