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
Related
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.
I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.
What are the alternatives?
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.
This is a function to store a float array to the phone external storage. Pass the file name.extension in the String name. You could modify it to export your file.
public static void save(float[] input_array, String name)
{
final String TAG2 = "->save()";
String string_array = Arrays.toString(input_array);
String fullName = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder/" + name;
String path = Environment.getExternalStorageDirectory().getPath() + "/SercanFolder";
File folder = new File(path);
if(!folder.exists())
{
folder.mkdirs();
}
BufferedWriter buf;
try
{
buf = new BufferedWriter(new FileWriter(fullName));
buf.write(string_array,0,string_array.length());
buf.close();
Log.d(TAG+TAG2, "array saved as document. ");
}
catch (IOException e)
{
Log.e(TAG+TAG2, "problems while saving the file. ");
}
}
The suggestion with getExternalStorage().getPath() (Thanks to blackapps) helped me to save the pdf in a folder, which can be opened in the file manager.
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.
I want to know whether it is possible to write data in /etc folder (or any other folder besides data)? If yes, how to do that?
And if not possible, any way to store a permanent data? For scenario example, an app is uninstalled (or clear data), but a specific file will still remain.
thank you.
i'm not sure about /etc folder, but the stuff saved in /data folder is managed by android automatically itself. So when you uninstall an app, anything related to it is also removed from data folder.
However, to store a file permanently besides Data folder on your SdCard, see the code below:
public static boolean saveOnFile(String msg){
boolean saved = false;
String filename = "yourFileName.extension";
try{
if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
File root = new File(Environment.getExternalStorageDirectory(), "/YourFolderOnSdCard/");
//create root folders if they do not exist
if(!root.exists()){
root.mkdirs();
}
//now lets save file in our directory structure
File file = new File(root, filename);
FileWriter fw = new FileWriter(file);
fw.append(msg);
fw.flush();
fw.close();
saved = true;
}
else
Log.e("Save", "Mounted media is not available or is write-protected");
}
catch (Exception e) { Log.e("Save", e.toString()); }
return saved;
}
This Data Storage guide could be useful.
is there a method that allows in Android 2.1 to create a new file and, if relative directories do not exist, to create them too?
make me know, 'cause this snippet does not work:
static String separator = File.separator;
public static final String DIRECTORYBIGLIETTI = "C:" + separator + "Users" + separator + "7-Spode" + separator + "Documents" + separator + "Android" + separator + "HUVWSZE"; ///sdcard/.SpodeApps/HUVWSZE/
public static final String FILEBIGLIETTI = DIRECTORYBIGLIETTI.concat(separator + "lista.txt");
File cartellainputoutput = new File(DIRECTORYBIGLIETTI);
if(!cartellainputoutput.exists())
{
cartellainputoutput.mkdirs();
}
File fileinputoutput = new File(FILEBIGLIETTI);
if(!fileinputoutput.exists())
try {
fileinputoutput.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
may i ask to the admin for upgrading this web site's graphics? ;)
You need to use mkdirs() to create the directories, and then create the file.
Just to make this clear, you cannot use Windows-like file paths (such as C:\Users\7-Spode\Documents\Android\HUVWSZE) in Android, you have to use Linux-like file paths (like /data/my.android.application/data_directory/file or /sdcard/directory/file.
Also, you should use methods such as getFilesDir() (for internal storage) and getExternalStorageDirectory() (for external storage, e.g. SD cards) to get those directories, and from there you can just create a regular File object and handle it from there.
Example (with internal storage):
File dir = getFilesDir(); // Returns a directory exclusively for this app.
File file = new File(dir, "directory/file");
file.mkdirs();
file.createNewFile();
Also note that when working with external storage, you should always check if external storage is unavailable (for instance if SD card has been removed, or the device is connected
to a computer), using getExternalStorageState().
For more information about how to use internal and external storage in Android, read this nifty article.
I want to create a directory on sd card keeping it as a separate activity in one of my application. I wrote the following code in the onCreate() of the application. It is not creating the directory though this code works fine if I try to implement it as an independent application.
Please suggest a solution for this problem.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
String dirName = "/sdcard/TEST";
File newFile = new File(dirName);
newFile.mkdirs();
Log.d("CaptureTest.java","Directory created");
if(newFile.exists()){
Log.d("capturetest.java","directory exists");
if(newFile.isDirectory()){
Log.d("capturetest.java","isDirectory = true");
}
else Log.d("capturetest.java","isDirectory = false");
} else
{
Log.d("capturetest.java","directory doesn't exist");
}
} catch(Exception e){
Log.d("capturetest.java","Exception creating folder " + e);
}
........................................
..........................................
}
The SD card might be mounted at /mnt/sdcard instead of /sdcard.
But the safest technique to get the external storage directory is like in the following code
File myDirectory = new File(Environment.getExternalStorageDirectory(), "my directory");
if(!myDirectory.exists()) {
myDirectory.mkdirs();
}
There could be a number of things causing this:
Check that external storage is available and writeable before trying to write to it.
Don't use String dirName = "/sdcard/TEST"; use Environment.getExternalStorageDirectory() or Context.getExternalFilesDir() instead.
This page has some really useful tips for correctly accessing the SD card.