File creation in Android - android

Can a xml file be created in Android just by creating an object of File class ie.
File FF=new File(Environment.getExternalStorageDirectory()+"//new.xml");
StreamResult result = new StreamResult(FF);
transformer.transform(source, result);
or
is it nececessary to use createNewFile() ie. FF.createNewFile()?
I've not written the detailed code here

Basically this should work if you requested the permission to write on the sd card. Add this to your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I personally open (for write) and create the files at once, except I want a 0 byte file for some kinds of checks e.g. as a kind of switch.

Related

Trying to save a file on an android system and make it downloadable by the user

I am sorry I am extremely new to android and I am lost. I successfully found out how to save a file on an android system, but every time I try to search for the file on my Android phone (which is where I have a copy of this app located) I am unable to locate it. I know it is there because the app would not start up with out it. How do you write a file that can be both used by the App AND searched by the user in the File Explorer. I am using a Galaxy Note 3 Android version 5.0 Any help would be appreciated.
private void WriteFile(String FileName, String FileCont, boolean isAppend){
File file = new File(getApplicationContext().getFilesDir().getAbsolutePath() + "/" + FileName);
try {
FileOutputStream stream = new FileOutputStream(file, isAppend);
stream.write(FileCont.getBytes());
stream.close();
}
catch(Exception ex){
}
}
Did set the permissions to write on external space in your manifest.xml?
For reference see
http://developer.android.com/reference/android/Manifest.permission.html
You have to set the "WRITE_EXTERNAL_STORAGE" permission to write on external disk. Just add the following line to your android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It will implicitly contain the permission to read external storage as well ;).

Why can i not make a directory inside Environment.DIRECTORY_PICTURES?

This is my code
File selfieLocation = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES),
"Daily Selfies");
boolean isDirectory = false;
if(!selfieLocation.isDirectory()) {
//Creates directory named by this file
selfieLocation.mkdir();
isDirectory = selfieLocation.isDirectory();
}
//array of strings
for(String selfiePath: selfieLocation.list()) {
selfies.add(selfiePath);
}
Basically what I am trying to do is create my own customizable directory inside of the standard directory in which to place pictures that are available to the user.
I looked at related threads and saw this one, Android: unable to create a directory in default pictures folder. However I made sure that I had a call to getExternal...., and not just have Environment.DIRECTORY_PICTURES as a parameter.
I also looked on here http://developer.android.com/guide/topics/data/data-storage.html#filesExternal and saw that I had the right method call/format to create a customizable folder in external memory. The docs example was
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
I stepped through my code and saw that the local variable isDirectory stayed at false even after the call to selfieLocation.mkdir(). Does anyone know why this directory cannot be created?
Try to create directory with File#mkdirs(), not File#mkdir(). The latter assumes that all parent directories are already in place, so it won't create directory if any of its parents don't exist.
Also, take a look at your permissions in AndroidManifest.xml. You need the following permissions in order to read/write the content on external storage:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
android.permission.READ_EXTERNAL_STORAGE isn't required for now, but it will be in the future releases of Android.

File Not Found Error reading SD Card

I'm writing an airplane simulator program and want the user to be able create model files seperately using XML. Then, in the app they can select which model (XML file) to load. I have the XML files in a subdirectory on my SD card and can read it with my BLU phone but not my Motorola Photon II. With the Motorola I get a file not found when initializing the input stream. I have the following code...
In the Manifest I have set read external storage permission...
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Here's the code to open the XML file...
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/SimFiles/Vehicles/" + "myModel.xml");
InputStream in = new BufferedInputStream(new FileInputStream(file));
It's pretty straight forward. So, why on one and not the other? Is it a permissions thing- one more strict than the other? Thanks.
Try using this...
File file = new File(Environment.getExternalStorageDirectory() + "/SimFiles/Vehicles/" + "myModel.xml");
InputStream in = new BufferedInputStream(new FileInputStream(file));

Android open file

I was trying to open a file for reading.
When using: Scanner input = new Scanner(filename); the file could not be found
but when I used:
InputStream in = openFileInput(filename);
Scanner input = new Scanner(in);
It worked. Why was the first line of code wrong?
Files are stored on the device in a specific, application-dependent location, which is what I suppose openFileInput adds at the beginning of the file name. The final result (location + file name) is constructed as follows:
/data/data/<application-package>/files/<file-name>
Note also that the documentation states that the openFileInput parameter cannot contain path separators.
To avoid hard-coding the location path, which could in principle even be different from device to device, you can obtain a File object pointing to the storage directory by calling getFilesDir, and use it to read whatever file you would like to. For example:
File filesDir = getFilesDir();
Scanner input = new Scanner(new File(filesDir, filename));
Note that constructing a Scanner by passing a String as a parameter would result in the scanner working on the content of the string, i.e. interpreting it as the actual content to scan instead of as the name of a file to open.
This drove me crazy couple of minutes ago. I forgot to add this line to manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I would expect a permission denied message. But just got a file not found...
In your case: openFileInput opens a file in your private app data directory (/data/data/your.package/filename). This never fails. But the scanner tries to open it on the root path. So when you want to read a file from SD card than you would use Environement.getExternalStorageDirectory().getAbsolutePath() + "/" + filename.
Scanner sc = new Scanner(new File(filename));

How to create a file in an SDCARD directory

I want to create a file(not created) in a directory(not created) in the SDCARD.
How doing it ?
Thank you.
Try the following example:
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//handle case of no SDCARD present
} else {
String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
//create folder
File folder = new File(dir); //folder name
folder.mkdirs();
//create file
File file = new File(dir, "filename.extension");
}
Don't forget to add the permission to your AndroidManifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is that mkdirs() is called on a File object containing the whole path up to the actual file. It should be called on a File object containing the Path (the directory) and only that. Then you should use another File object to create the actual file.
You should also have to add permission to write to external media.
Add following line in the application manifest file, somewhere between <manifest> tags, but not inside <application> tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Use This:
DocumentFile tempDir = DocumentFile.fromSingleUri(context,targetDirectoryUri);
DocumentFile newDocumentFile = tempDir.createFile(type,name);
"targetDirectoryUri" is uri of the directory you want to put the file into it.
This is the only solution!
After Api 19 you can not write on SDCard, so you must use DocumentFile
instead File.
In addition, you must also take SDCard permission. To learn how to do this and get the targetDirectoryUri, please read this.
You can use in Kotlin
val file = File( this.getExternalFilesDir(null)?.getAbsolutePath(),"/your_image_path")
if (!file.exists()) {
file.mkdir()
}
Don't forget to give permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
See here why creating files on root of the SD card is a bad idea

Categories

Resources