Creating and reading a one time created file - java

I want to store a list of strings in a file.
I need to create it just one time, and after that i will read and write on it programmaticlly.
My question is where in the file system should i create the file (manually) so that it will best for reading and writing ?
Thanks.

You can create your file in your app's directory so no one can access it but your app
getApplicationContext().getFilesDir().getAbsolutePath();
or on sd card
File externalStorage = Environment.getExternalStorageDirectory();
if you want others to access it and, maybe, if your file is very big
If you intent to create your file manually then I think SD card is the only option unless you have a rooted phone or working with the emulator.

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
//SDcard is there
File f=new File("/sdcard/YOURFILE.txt");
if (!f.exists())
{
//File created only for first time
f.createNewFile();
//create inputstream and write it to your file
OutputStream out=new FileOutputStream(f);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
System.out.println("\nData Written");
}
else { // read/ write SECOND TIME }
}

It really depends.
The problem with creating the file on the SDCard is that a special permission is required in order to access it. If the app is only for yourself, that's cool. If you want to distribute it through Google MarketPlay (or whatever it is called these days), please know that some people (myself included) tend to look at the permissions and ask "why would an app doing X require permission to do Y?", and sometimes not install the app because of it.
If the manual part is done by the app's user, by all means, store it on the sdcard. It's the only place a standard, none-root user even has access to.
Generally speaking, however, a better place to store data is in /data/data/packagename. See Android's data storage for more details.
Shachar

Add file in assets folder, then it will be clearly after new install

Related

Android File not being copied to SD card

I'm trying to copy a file that is located in the External storage directory into a directory that is in my SD Card. However, when I check to see if the file has successfully been copied, the file is not even created in the SD Card.
Am I missing something? Here is the code I have:
String sourcePath = Environment.getExternalStorageDirectory().getPath() + newFileName;
File source = new File(Environment.getExternalStorageDirectory().getPath(), newFileName);
String destinationPath = "/storage/external_SD";
File destination = new File(destinationPath, newFileName);
try {
if(!destination.exists()){
destination.mkdir();
}
FileUtils.copyFile(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
The copyFile method is from an Apache library. Here is the link for it: https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
However, when I check to see if the file has successfully been copied, the file is not even created in the sd Card.
You do not have arbitrary filesystem-level access to removable storage on Android 4.4+.
Is there a work around for this?
That depends on what your objective is.
If you insist that you must be able to write to that specific path on arbitrary user devices... then, no, there is no supported workaround. After all, there is no /storage/external_SD on the vast majority of Android devices. Where and how device manufacturers choose to mount removable media is up to them and is an implementation detail that will vary.
If you relax that restriction, but insist that you must be able to write a file to the root directory of removable storage on arbitrary user devices... then, no, there is no supported workaround today. The N Developer Preview has a "Scoped Directory Access" feature that should allow this, but it will be several years before you can assume that an arbitrary user device will be running that version of Android or higher. Also, you do not get actual filesystem access, but rather a Uri (see the Storage Access Framework option, below).
Now, if you are more flexible about the precise location, you have other options:
You can use getExternalFilesDirs(), getExternalCacheDirs(), and getExternalMediaDirs(), all methods on Context. Note the plural form. If those return 2+ entries, the second and subsequent ones are locations on removable storage that you can read from and write to, no permissions required. However, you do not get to choose the exact path. And if the device has 2+ removable storage volumes, I'm not quite certain how you would help the user tell them apart.
You can use the Storage Access Framework and let the user choose where to put the file. The user is welcome to choose removable storage... or not. You get a Uri back, which you can use with ContentResolver and openOutputStream() to write your content. You can also take persistable Uri permissions so you can work with that file again in the future, assuming the user doesn't move or delete it behind your back.
If you want to copy to external storage then you need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The destinationPath you mentioned may not be accessible as it may belong to the private system folders or some other application folders. You can however use public folders like Pictures,Music, Videos,Downloads,etc. or create sub folders inside them -
String sourcePath = Environment.getExternalStorageDirectory().getPath() + newFileName;
File source = new File(Environment.getExternalStorageDirectory().getPath(), newFileName);
File destinationPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS, "/external_SD");
try {
if(!destinationPath.exists()){
destinationPath.mkdir();
}
File destination = new File(destinationPath, newFileName);
FileUtils.copyFile(source, destination);
} catch (IOException e) {
e.printStackTrace();
}

Writing files to external storage in Android failing

As the title points out, I'm having trouble writing files to the external storage. My debug device is a Nexus 5. The thing is, I'm able to read files perfectly from the device (I've been trying with the ones in the Download Folder) but cannot write them. I am aware that I must do this while the device isn't connected to the computer. But it doesn't work either.
In fact, I've tried reading the state of the SD card prior to writing to it (which didn't work, of course). The state showed as "mounted" either when the device was connected to my PC or not. And I compared the state to Environment.MEDIA_MOUNTED_READ_ONLY and Environment.MEDIA_MOUNTED without any success. My device is in none of these states.
One thing which you must know is that my phone doesn't have an external SD card, as it's an internal one. This results in my device having a "/storage/emulated/0/..." directory for the external storage.
I must also point out that I have implemented the following tags in my Android Manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE"/>
I don't have any clue to what might be happening. Another thing which might help is that I've tried managing files with winrar (for Android) and I've been able to remove files with the device connected to my PC as well as without having it connected. So I don't know what to do.
The code which I'm using to write a file is the following. Bear in mind that it should read an image file (which it does), convert it into a string, convert it back into an image and then save it to the Downloads Folder:
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + "/base_image.jpg");
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
String imageDataString = encodeImage(imageData);
// Converting a Base64 String into Image byte array
byte[] imageByteArray = decodeImage(imageDataString);
File newFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "converted_image.jpg");
//Write a image byte array into file system
FileOutputStream imageOutFile = new FileOutputStream(newFile);
imageOutFile.write(imageByteArray);
imageInFile.close();
imageOutFile.close();
What should I do?
Just fix ANDROID.PERMISSION.WRITE_EXTERNAL_STORAGE to android.permission.WRITE_EXTERNAL_STORAGE in your uses-permission.
I've encounterd this problem, UPPERCASE in permission is not useful.
FileOutputStream does NOT automatically create a file if it's not exist.
So, you need to check and create if your file doesn't exist.
if(!newFile.exists()) {
newFile.createNewFile();
}
Hope this help!

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

Creating a .txt file from scratch

I'm working on a microcontroller and I'm trying to write some data from some sensors into a .txt file on the SDcard and later on place the sd card in a card reader and read the data on the PC.
Does anyone know how to write a .txt file from scratch for a FAT32 file system? I don't have any predefined code/methods/functions to call, I'll need to create the code from nothin.
It's not a question for a specific programming language, that is why I tagged more than one. I can later on convert the code from C or Java to my programming language of choice. But I can't seem to find such low level methods/functions in any type of language :)
Any ideas?
FatFs is quite good, and highly portable. It has support for FAT12, FAT16 and FAT32, long filenames, seeking, reading and writing (most of these things can be switched on and off to change the memory footprint).
If you're really tight on memory there's also Petit FatFs, but it doesn't have write support by default and adding it would take some work.
After mounting the drive you'd simply open a file to create it. For example:
FATFS fatFs;
FIL newFile;
// The drive number may differ
if (f_mount(0, &fatFs) != FR_OK) {
// Something went wrong
}
if (f_open(&newFile, "/test.txt", FA_WRITE | FA_OPEN_ALWAYS) != FR_OK) {
// Something went wrong
}
If you really need to create the file using only your own code you'll have to traverse the FAT, looking for empty space and then creating new LFN entries (where you store the filename) and DIRENTs (which specify the clusters on the disk that will hold the file data).I can't see any reason for doing this except if this is some kind of homework / lab exercise. In any case you should do some reading about the FAT structure first and return with some more specific questions once you've got started.
In JAVA you can do like this
Writer output = null;
String text = "This is test message";
File file = new File("write.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(text);
output.close();
System.out.println("Your file has been written");

Avoiding fragmentation when saving files to BlackBerry filesystem. Best practice?

In my application I need to save some file (a pdf) to the filesystem. My current method involves creating a directory for storing the files:
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/pdfs/");
if (!fc.exists())
fc.mkdir();
fc.close();
I then write to the directory with my file:
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/pdfs/" + filename, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(pdf);
outStream.close();
fc.close();
This all works fine, and my pdf arrives in my created directory. My question is: will I run into trouble with the fact that I have hard coded a file path as my save destination. With the BlackBerry API is it possible to retrieve a writeable folder which exists on all models/configurations?
You can query the system for the available roots using FileSystemRegistry.listRoots(). Note that it is not guaranteed that there will be an sdcard, or that it will be visible even if there is one (when in mass storage mode, for instance). I think that the only root guaranteed to be on all devices is internal storage ("file:///Store").
There's (a little) more information here.

Categories