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
Related
The below code doesn't create a folder in my device.
String intStorageDirectory = context.getFilesDir().toString();
File folder = new File(intStorageDirectory, "test");
folder.createNewFile();;
I need a folder created for my app to store media, when user installs it. That folder should be visible on file explorer. How can i do it?
With the current snippet you created a file, you can also create folder by creating file but your current directory is the base folder, getFilesDir() points internal storage for your app which not visible nor accessible unless explicitly declared. You can create a folder and file by creating with new File().createNewFile() or create only folder using mkdirs() but you won't be able to display it using a file explorer app and that folder and files inside it will be deleted when/if user uninstalls your app.
To save files externally(This doesn't mean saving to SD Card) you can create directory and file with
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), folderName);
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs()
}
File mediaFile = new File(mediaStorageDir.getAbsolutePath() + File.separator + fileName);
And you need some kind of OutputStream to write data to that file.
Make sure that you ask <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> inside your AndroidManifest.xml file and ask write permission on runtime if your android:targetSdkVersion="23" or above
new File(context.getFielsDir(), "test").mkdirs();
createNewFile creates a file, not a folder. Using mkdirs instead of mkdir ensures that all parents exist. There's also no reason to go through a string when you already have a File.
Adding folder.mkdirs(); should work in place of folder.createNewFile(); And don't forget to add the permissions.
This will create a folder in you data directory.
And just a suggestion , if you want to store media in a SD card folder maybe Environment.getExternalStorageDirectory() is good.
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);
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).
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");