I want to save a file on internal storage into a specific folder. My code is:
File mediaDir = new File("media");
if (!mediaDir.exists()){
mediaDir.createNewFile();
mediaDir.mkdir();
}
File f = new File(getLocalPath());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(data);
fos.close();
getLocalPath returns /data/data/myPackage/files/media/qmhUZU.jpg but when I want to create the media folder I'm getting the exception "java.io.IOException: Read-only file system". Any ideas how to write my files on internal phone storage in in folder media? Thanks.
You should use ContextWrapper like this:
ContextWrapper cw = new ContextWrapper(context);
File directory = cw.getDir("media", Context.MODE_PRIVATE);
As always, refer to documentation, ContextWrapper has a lot to offer.
You should create the media dir appended to what getLocalPath() returns.
I was getting the same exact error as well. Here is the fix. When you are specifying where to write to, Android will automatically resolve your path into either /data/ or /mnt/sdcard/. Let me explain.
If you execute the following statement:
File resolveMe = new File("/data/myPackage/files/media/qmhUZU.jpg");
resolveMe.createNewFile();
It will resolve the path to the root /data/ somewhere higher up in Android.
I figured this out, because after I executed the following code, it was placed automatically in the root /mnt/ without me translating anything on my own.
File resolveMeSDCard = new File("/sdcard/myPackage/files/media/qmhUZU.jpg");
resolveMeSDCard.createNewFile();
A quick fix would be to change your following code:
File f = new File(getLocalPath().replace("/data/data/", "/"));
Hope this helps
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
Hi try this it will create directory + file inside it
File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
mediaDir.mkdir();
}
File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();
System.out.println("Your file has been written");
Related
I want to download some data and store it into a file. I am aware that I cannot write to the assets dir or any other place because of the sole nature of the APK file.
I am wondering, if I create a file with something like:
FileOutputStream fileout = openFileOutput("text.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
outputWriter.write("write this string to file.");
outputWriter.close();
Since I cannot write any files to assets or any raw dir, where it will be written?
What will the location of that file be? Where will it be located in the Android file system ?
Since I cannot write any files to assets or any raw dir, where it will be written?
openFileOutput() writes to internal storage.
What will the location of that file be? Where will it be located in the Android file system ?
That can vary by device and user. It will be to the same directory that is returned via a call to getFilesDir().
You can get the path to your file created with openFileOutput like this: MainActivity.this.getFilesDir().getAbsolutePath()+"/text.txt" and you can read it using an object of FileInputStream FileInputStream fis = new FileInputStream(new File(MainActivity.this.getFilesDir().getAbsolutePath()+"/text.txt"));
in my app I am seeing few crashes when I try to create a directory structure under the application internal storage, such as /data/data/[pkgname]/x/y/z....
Here is the failing code:
File clusterDirectory = new File(MyApplication.getContext().getFilesDir(), "store");
File baseDirectory = new File(clusterDirectory, "data");
if (!baseDirectory.exists()) {
if (!baseDirectory.mkdirs()) {
throw new RuntimeException("Can't create the directory: " + baseDirectory);
}
}
My code is throwing the exception when trying to create the following path:
java.lang.RuntimeException: Can't create the directory: /data/data/my.app.pkgname/files/store/data
My manifest specifies the permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />, even if it should not be necessary for this purpose (it is actually necessary for my apps due to Google Maps Android API v2).
It doesn't seem to be related to the phone, since I get this exception on old phones as well as on new ones (last crash report is Nexus 4 with Android 4.3).
My guess is that the directory /data/data/my.app.pkgname doesn't exist in the first place but mkdirs() can't create it because of permissions issues, could that be possible?
Any hints?
Thanks
Use getDir(String name, int mode) to create directory into internal memory. The method Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory.
So example is
// Create directory into internal memory;
File mydir = context.getDir("mydir", Context.MODE_PRIVATE);
// Get a file myfile within the dir mydir.
File fileWithinMyDir = new File(mydir, "myfile");
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
For nested directories, you should use normal java method. Like
new File(parentDir, "childDir").mkdir();
So updated example should be
// Create directory into internal memory;
File mydir = getDir("mydir", Context.MODE_PRIVATE);
// Create sub-directory mysubdir
File mySubDir = new File(mydir, "mysubdir");
mySubDir.mkdir();
// Get a file myfile within the dir mySubDir.
File fileWithinMyDir = new File(mySubDir, "myfile");
// Use the stream as usual to write into the file.
FileOutputStream out = new FileOutputStream(fileWithinMyDir);
I am in need to create a text file where the input is taken from the user.
I am trying to save the txt file in a folder(folder should be created even if it is not there)
My code is as follows,
FileOutputStream fileos = null;
if (FreeMemory() != 0) {
FileOutputStream fos=null;
try {
File path=new File(getFilesDir(),"sri");
if(!path.exists()){
path.mkdir();
}
File mypath=new File(path,"myfile.txt");
if (!mypath.exists()) {
fos = new FileOutputStream( mypath);
String text="Write Hii";
fos.write(text.getBytes());
fos.close();
}
}catch(Exception e){
}
}
The "path" variable gives this path: "/data/data/com.example.gm/files/sri"
I navigated to this path in my device: Android-->Data-->com.example.gm-->files-->
but the folder "sri" is not created and even the file also. Am I navigating to th ecorrect path ? I am not able to find out the file in the device.
I searched for the folder by installing "Astro File Manager" app too. But, couldn't find it. I am not getting any Exception when writing to the folder. The code must be correct. But where is the folder and file? Please anyone help me in solving this.
I want to save the txt file in internal memory of my device.
Whats wrong with my code? Please suggest me the solution.
I have gone through many trails and finally approached stackoverflow.
Thanks for any help!!
The data in the internal storage is not accessible out side the application owning it, so any third party application like file browser or Astro File Manager will not be able to see the files. The application with root access will only be able to access the files in the internal memory. I believe you should programmatically verify if the file is created. getFilesDir() will give the internal memory location allocated to that app.
Have you give the permission in manifiest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
A few WAV files used by my app are currently located in res/raw. These files need to be accessible by the user after the app is installed. So ideally my app should create a folder on the device and put the files in it. Any idea/suggestions on how to do this?
soundIds[0] = soundPool.load(test2Activity, R.raw.snare, 1);
soundIds[1] = soundPool.load(test2Activity, R.raw.snare2, 1);
You can access the sd_card, so you can create a directory and put there your files
// create a File object for the parent directory
File yourDirectory = new File("/sdcard/YourDirectory/");
// have the object build the directory structure, if needed.
yourDirectory.mkdirs();
// create a File object for the output file
File outputFile = new File(yourDirectory, filename);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
The output file should be your sound that you have loaded from res/raw.
My advice would be to just copy the sound to the folder, and still use the sound from res/raw from within your app because
1) it is easier since you can access it as a resources
2) you are sure the user didn't deleted the directory.
Remember to put the user permission "android.permission.WRITE_EXTERNAL_STORAGE" in the manifest
Android gives you getDir (I assume this means I would have myappspace/somedirectory) to create a directory in you application space. But how do you read or write to a file in that directory when android gives you an error if you have the path separator in the openFileOutput/Input call it gives you an error?
getDir returns a File object. To manipulate the directory and file structure, you continue to use File objects. For example
File dir = getDir("myDir", Context.MODE_PRIVATE);
File myFile = new File(dir, "myFile");
the openFileOutput simply returns a FileOutputStream based on some text criteria. All we have to do is create the object
FileOutputStream out = new FileOutputStream(myFile);
From here, you continue as normal.
String hello = "hello world";
out.write(hello.getBytes());
out.close();
FileInputStream would follow the same guidelines.
The point is that openFileInput() and openFileOutput() work with files in that directory directly so they don't need an absolute pathname.
EDIT: More accurately, they work with files in the directory returned by getFilesDir() rather than getDir() which is normally the package root.
If you want to create custom directories relative to getDir(), then you'll need to use classes/methods other than openFileInput() and openFileOutput() (such as using InputStream and OutputStream and relevant file 'reader' / 'writer' classes).