Can you create a .dat file in Android - android

I am trying to write my first app for Android. I knew Java formerly but it has been a year or two since I used it.
I want to create a simple file in internal storage - I understand I do not have to set any permissions to create such a file?
Is it a .dat file I need if I want to save an ArrayList? Does Android require me to use file extension when creating it?
Even with just trying the basic file creation - checking for existence of file and then creating it if it does not exist - does not work. Can anyone tell me what I am doing wrong?
(I have commented out the attempt to read the ArrayList, as I cannot even create the file. Just trying the basic file creation.)
(Also, I have tried the code with "Shares.dat" instead of just "Shares" as filename, that didn't work either. I don't even know whether Android recognises .dat files and to be honest I am not 100% sure that is the file I need.)
(If by any chance anyone can help, I may not be able to test any solution until next weekend......)
As for the last but one line, originally it read 'context.getFileDir()' but my class extends ActionBarActivity and I found on internet a suggestion to change to this.getFileDir(). I got a null pointer warning when I used context.getFileDir()
file = new File("Shares");
if (file.exists()){
url.setText("File Exists");
/*try{
is = openFileInput("Shares");
oi = new ObjectInputStream(is);
details = (ArrayList<Action>)oi.readObject();//warning
oi.close();//need finally??
}
catch(Exception e){url.setText((e.getMessage()));}
url.setText(details.get(0).getAddresse());*/
}
else
{
try
{
**file = new File(this.getFilesDir(), "Shares");**
}
catch(Exception e){url.setText((e.getMessage()));}
}

If you want a reference to a file that's created in private storage, you'd want to use getFileStreamPath("shares.dat") instead of creating a new File object. File extension shouldn't matter, but it's a good practice to add a file extension to keep track for yourself what those files are for.
For example:
private boolean fileExists(Context _context, String _filename) {
File temp = _context.getFileStreamPath(_filename);
if(temp == null || !temp.exists()) {
return false;
}
return true;
}
Then, if you wanted to write to a file named "shares.dat" then you'd use openFileOutput("shares.dat", Context.MODE_PRIVATE). If you wanted to read in from that file, you'd use openFileInput("shares.dat").
// Read in from file
if(fileExists(this, "shares.dat")) {
FileInputStream fis = this.openFileInput("shares.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Action> actions = (ArrayList<Action>)ois.readObject();
ois.close();
}
// Write out to file
FileOutputStream fos = this.openFileOutput("shares.dat", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(actions);
oos.close();
All stream operations shown above have the ability to throw an IOException, so be sure to wrap that code in a try/catch block as needed.

Related

Creating a file unsing openFileOutput() which is visible to other applications

I'm using the openFileOutput() to create a new txt file. I need the file to be visible from other applications (as well as from a PC when the Android device is connected via USB. Ive tried using .setReadable(true); but this does not seem valid. Please advise how I should declare the file is visible / public.
try {
textIncoming.append("saving");
final String STORETEXT = "test.txt";
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(STORETEXT, 0));
out.setReadable(true);
out.write("testing");
out.close();
}
catch (Throwable t) {
textIncoming.append("not saving");
}
Ive changed my program to use getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), but for some reason it returns a path /storage/emulated/0/Documents, and I cant even find this folder on the device. Ive looked at the files on the android device using ES file explorer but cant find the folder or file I'm trying to create (Plus I want these in an documents folder on the SD card, so it seems that its not giving me a pointer to the SD card at all, and not creating the folder, and not creating the file. Following is my updated code, please advise
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();
File myDir = new File(root + "/Saved_Receipts");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "DRcpt-" + n + ".xml";
textIncoming.append(root);
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
Save it to sdcard if you want anyone to be able to read it.
This android documentation should tell you what you need to do.
https://developer.android.com/guide/topics/data/data-storage.html#filesExternal
openFileOutput() documentation says:
Open a private file
So the file that it creates won't be visible to other apps, unless you copy it to another directory that is visible. In that case, you have to save your data in what's called "external storage" which is shared with other apps. Use the code at this link.

Why a File returned by ContextWrapper.getDir() always exists?

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
}

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.

Default dir to store a file that my app makes

A question, I'm making a app that will store a textfile (.txt) with highscore data. I've made a file with this line from my highscores activity:
File highscoreList = new File("highscores.txt");
Where will it be placed? In the same dir as the highscores.java file? Or, how should I specify a dir that will put the textfile in the same folder as highscores.java?
You should access your files using the Context methods openFileInput and openFileOutput. You can determine where they are actually stored using getFileStreamPath. (The directory they go in can be obtained with getFilesDir.) The advantage of using this method is that the files will be private to your application and will be removed automatically if your app is uninstalled.
In your activity, you can create your File with:
File highscoreList = getFileStreamPath("highscores.txt");
If all you want to do is write to it:
FileOutputStream output = null;
try {
output = openFileOutput("highscores.txt", MODE_PRIVATE);
// write to file
} finally {
if (output != null) {
try { output.close(); }
catch (IOException e) {
Log.w(LOG_TAG, "Error closing file!", e);
}
}
}
Similarly, for reading you can use:
FileInputStream input = openFileInput("highscores.txt");
If you are trying to access your file from outside an Activity subclass, you'll need a Context. (In a View, for instance, you can use getContext(). For a helper class, you'll need to pass in your Activity instance or some other Context object.)

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