In my application I want to save some documents in my application cache. After use I want to clear that files from cache. If I clear the cache all saved data's will be loss but I don't want that. I need to create a sub folder under my cache and I want to read data's from that cache folder also after certain uses I wanted to clear data's present in that particular folder.
How can I do that using getExternalCacheDir()?
I tried using following snippet,
File tempFile = new File(AppDelegate.sharedDelegate().getExternalCacheDir()+"\documentfolder\", name + ext);
OutputStream outputStream = new FileOutputStream(tempFile);
IOUtils.copy(inputStream, outputStream);
outputStream.close();
return tempFile;
But I am getting
System.err: java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.package.debug/cache/documentcache/Screenshot_20171108-011217.png.png (No such file or directory)
W/System.err: at java.io.FileOutputStream.open(Native Method)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:221)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
How can I solve it?
getCacheDir(). It returns the absolute path to the application specific cache directory
File myDir = new File(getCacheDir(), "yourfolder");
myDir.mkdir();
then create file using below code.
File f = new File(your directyorypath + "filename.txt");
if (f.exists())
{
f.delete();
}
f.createNewFile();
This should work:
File dir = new File(AppDelegate.sharedDelegate().getExternalCacheDir(), "documentfolder");
dir.mkdirs();
then use dir as parent folder for your file:
File tempFile = new File(dir, name + ext);
OutputStream outputStream = new FileOutputStream(tempFile);
IOUtils.copy(inputStream, outputStream);
outputStream.close();
return tempFile;
Related
I try this file writer/reader code segment for test:
File file = new File(Environment.getExternalStorageDirectory(), "LM/lm_lisdat_01.txt");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(("test").getBytes());
outputStream.close();
File file = new File(getExternalFilesDir(null), "LM/lm_lisdat_01.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
In the 4. row i got this error message below but the "lm_lisdat_01.txt" file was created in LM directory:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/hu.abisoft.lm/files/LM/lm_lisdat_01.txt: open failed: ENOENT (No such file or directory)
Can help anyone for answer this (i think simple) question? I'm newby in Android. Thank you!
You are creating the file in one directory and trying to open it for input in another.
Environment.getExternalStorageDirectory() is /storage/emulated/0
getExternalFilesDir(null) is /storage/emulated/0/Android/data/hu.abisoft.lm/files
Use the same directory for file creation and input.
With sdk, you can't write to the root of internal storage. This cause your error.
Edit :
Based on your code, to use internal storage with sdk:
final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");
Please see changes. Your path was wrong.
And also check whether file exists or not.
File file = new File(Environment.getExternalStorageDirectory(), "LM/lm_lisdat_01.txt");
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(("test").getBytes());
outputStream.close();
File file = new File(Environment.getExternalStorageDirectory(), "LM/lm_lisdat_01.txt");//changes here
if(file.exists())
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
}
I create a folder called "res" inside sdcard
File f = new File(Environment.getExternalStorageDirectory() + "/res/");
f.mkdirs();
The folder is successfully created.
But when I try to create a file within the folder does not work.
String string = "hello!";
File file = new File(Environment.getExternalStorageDirectory() + "/res/","test.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
LOGCAT
java.io.FileNotFoundException: /mnt/sdcard/res/test.txt (Not a directory)
The call to new File() doesn't actually create the file. You need to check if the file exists by using file.exists(). If it doesn't, you must create the file by calling file.createNewFile(). See this answer for sample code: https://stackoverflow.com/a/7012122/379245
I have tried so many ways to write file in external as card but not working. Please suggest me what to do.
The code snippet that I wrote is as follows:
final String directoryFile = "file:///"+"mnt/extsd/Test";
String filename = "TextData.txt";
Context context;
//String file=Environment.getExternalStorageDirectory()+ "/TextData.txt";
//String file = "mnt/extsd/TextData.txt";
//String file=Environment.getExternalStorageDirectory()+ "/RudimentContent/test.txt";
//File root = android.os.Environment.getExternalStorageDirectory();
//File dir = new File (root.getAbsolutePath() + "/download");
//File path = Environment.getExternalStorageDirectory();
//String filename = "TextData.txt";
//String fileName = "TextData.txt";
//String path = "Environment.getExternalStorageDirectory()/TextData.txt";
//File path = Environment.getExternalStorageDirectory();
public void onClick(View v)
{
// write on SD card file data in the text box
// dir.mkdirs();
//File file = new File(dir, "myData.txt");
//String fileName = surveyName + ".csv";
//String headings = "Hello, world!";
//File file = new File(path, fileName);
//path.mkdirs();
//OutputStream os = new FileOutputStream(file);
//os.write(headings.getBytes());
//create path
//create file
//File outFile = new File(Environment.getExternalStorageDirectory(), filename);
//File directoryFile = new File("mnt/extsd", "Test");
//directoryFile.mkdirs();
//create file
//File file = new File(Environment.getExternalStorageDirectory(), filename);
try{
File myFile = new File(directoryFile, filename); //device.txt
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD "+myFile.getPath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
I have commented on so may tried codes also. When I write in internal sd card then its working but not with external. Please suggest.
I had this before.
The reason you're having this exception is due to some bizarre ways the framework handles files and folders.
on my case was that I was testing, and all was working, and I deleted the testing folder and since then the system keeps trying to write on the deleted folder. I removed the project from the phone and reboot it and started working again.
furthermore, I suggest you a quick reading on this answer What is the best way to create temporary files on Android? and the comments of this answer... as there is a lot of useful information if you want to create a good app.
just set permission like this
android.permission.WRITE_EXTERNAL_STORAGE
If you're using API Level 8 or greater, use getExternalFilesDir() to open a File that represents the external storage directory where you should save your files. This method takes a type parameter that specifies the type of subdirectory you want, such as DIRECTORY_MUSIC and DIRECTORY_RINGTONES (pass null to receive the root of your application's file directory).
This method will create the appropriate directory if necessary.
If you're using API Level 7 or lower, use getExternalStorageDirectory(), to open a File representing the root of the external storage. You should then write your data in the following directory:
/Android/data//files/
You will have to set the permissions too:
android.permission.WRITE_EXTERNAL_STORAGE
try this
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
and add this in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT: By using this line you can able to see stores images in the gallery view.
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
I may be way off here, but I am trying to download a file and store it in the downloads folder on my phone. I am getting a "java.io.FileNotFoundException" error, because the file doesn't exist, because I'm trying to download it...what am I doing wrong?
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File dir = new File(PATH);
dir.mkdirs();
File outputFile = new File(dir, "downloadFile");
FileOutputStream fos = new FileOutputStream(outputFile);
This fails, with the following:
java.io.FileNotFoundException: /mnt/sdcard/download/downloadFile (Permission denied)
I am using the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permissions....
Please try following updated code,
String PATH = Environment.getExternalStorageDirectory() + "/download";
File dir = new File(PATH);
dir.mkdirs();
File outputFile = new File(dir, "downloadFile");
if ( !outputFile.exists() )
{
outputFile.create();
}
FileOutputStream fos = new FileOutputStream(outputFile);
There is a "/" after the download. This way Android is thinking that you are creating Recursive Directory. While using mkdirs(), you can not create recursive directories.
You can also check my answer for same in Java ME here.
Add Permission to write external memory in your Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here you want to make directoy?
it there is already folder of download than use this code directly.
// create a File object for the parent directory
File Directory = new File("/sdcard/download/");
Directory.mkdirs();
// create a File object for the output file
File outputFile = new File(Directory, downloadFile);
// now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fos = new FileOutputStream(outputFile);
It might be wise to use Environment.getExternalStorageDirectory() for getting the "SD Card" directory as this might change
I have a little issue with creating folders for my application in Internal Memory. I'm using this piece of code :
public static void createFoldersInInternalStorage(Context context){
try {
File usersFolder = context.getDir("users", Context.MODE_PRIVATE);
File fileWithinMyDir = new File(usersFolder, "users.txt"); //Getting a file within the dir.
FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.
File dataFolder = context.getDir("data", Context.MODE_PRIVATE);
File fileWithinMyDir2 = new File(dataFolder, "data.txt"); //Getting a file within the dir.
FileOutputStream out2 = new FileOutputStream(fileWithinMyDir2); //Use the stream as usual to write into the file.
File publicFolder = context.getDir("public", Context.MODE_PRIVATE);
File fileWithinMyDir3 = new File(publicFolder, "public.txt"); //Getting a file within the dir.
FileOutputStream out3 = new FileOutputStream(fileWithinMyDir3); //Use the stream as usual to write into the file.
} catch(FileNotFoundException e){
e.printStackTrace();
}
}
So folders are created but in front of their name there is the beginning "app_" : app_users, app_data, app_public. Is there a way to create the folders with the name given by me? And another question : I want to first create folder Documents and than all other folders "Data, Public, Users" on it.... And the last question : How can I give the right folder path if I wanted to create a file in Documents/Users/myfile.txt in Internal Memory?
Thanks in advance!
You can use this :
File myDir = context.getFilesDir();
String filename = "documents/users/userId/imagename.png";
File file = new File(myDir, filename);
file.createNewFile();
file.mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(mediaCardBuffer);
fos.flush();
fos.close();
Is there a way to create the folders with the name given by me?
Use getFilesDir() and Java file I/O instead of getDir().
How can I give the right folder path if I wanted to create a file in Documents/Users/myfile.txt in Internal Memory?
Use getFilesDir() and Java file I/O, such as the File constructor that takes a File and a String to assemble a path.