File isn't getting created in the phone's external storage - android

I have used this code for creating a file in my Phone's external storage. Please note that I've set the permissions for Read and Write in my Manifest file.
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
String bodyOfFile = "Body of file!";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bodyOfFile.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
My LogCat is showing the below. I can't see the file 20170602.txt in that particular location. In my Download folder, there isn't any file with that name. Can anyone tell me where I went wrong.
D/tag: Directory: /storage/emulated/0/Android/data/com.pc.tab/files/Download
D/tag: File: /storage/emulated/0/Android/data/com.pc.tab/files/Download/20170605.txt
UPDATE:
I'm using MOTO G4 for running this app. I found the 20170602.txt file on Internal Storage.
File Manager --> `LOCAL` tab ( Upper right ) --> Internal Storage --> Android --> data --> com.pc.tab --> files --> Download --> 20170602.txt

It is important to separate the directory and the file itself
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
In your code you call mkdirs on the file you are want to write on, its an error because mkdirs makes your file be an a directory. You should call mkdirs for the directory only so its will be created if its not exist, and the file will be created automatically when you create new FileOutputStream object for this file.
Your code should look like this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt"; //like 20170602.txt
File directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(directory, fileName);
String bodyOfFile = "Body of file!";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(bodyOfFile.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}

Related

Save image in current view to sdcard using Android universal-image-loader

I'm a newbie Android developer. I have loaded an image using universal-image-loader and I would like to save it on my sd card. The file is created in the desired directory with the correct filename, but it always has a size of 0. What am I doing wrong?
A relevant snippet follows:
PS: The image already exists on disk, it's not being downloaded from the Internet.
private void saveImage(String imageUrls2, String de) {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
File SDCardRoot = Environment.getExternalStorageDirectory()
.getAbsoluteFile();
String filename = de;
File myDir = new File(SDCardRoot+"/testdir");
Bitmap mSaveBit = imageLoader.getMemoryCache();
File imageFile = null;
try {
//create our directory if it does'nt exist
if (!myDir.exists())
myDir.mkdirs();
File file = new File(myDir, filename);
if (file.exists())
file.delete();
FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
bos.flush();
bos.close();
} catch (IOException e) {
filepath = null;
e.printStackTrace();
Toast.makeText(getApplicationContext(),
R.string.diskful_error_message, Toast.LENGTH_LONG)
.show();
}
Log.i("filepath:", " " + filepath);
}
Yes, your code creates an file on sdcard_root/testdir/de only, and didn't write anything to it. Is "imageUrls2" the source image file? If yes, you can open that file with BufferedInputStream, read the data from BufferedInputStream, and copy them to output file with bos.write() before bos.flush() and bos.close().
Hope it helps.

Writing File in External SD card in android

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())));

Folder created on android sd card, but file not created

I think I have looked at all of the relevant questions and I still can't get this to work.
Here is the code:
File sdCard = Environment.getExternalStorageDirectory();
File directory= new File (sdCard.getAbsolutePath() + appName);
directory.mkdirs();
File file = new File(directory,fileName);
The folder is created, but I get an error saying the file does not exist. appName is a string containing the name of the folder and that works correctly. fileName is a string containing the name of the file I want to include.
I have included the permission in the manifest.
What am I doing wrong?
Update:
The code tries to make a subdirectory and a file at the same time, which hidden because the code uses a named String rather than a String literal. Adding an intermediate step to create the subdirectory solved the problem.
If the directory is created, then you're on the right track. In your code you are not actually creating the file on the SD card. If you need to create the file, then do this:
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard.getAbsolutePath() + appName + "/" + fileName);
directory.mkdirs();
file.createNewFile()
This is notional only. It would be much better to actually separate your fileName into a separate subfolder and the actual file and handle them separately.
Try this out:
In this I am creating a text file (.txt file) of a string.
public void createFileFromString(String text)
{
File logFile = new File("sdcard/xmlresponseiphone.txt");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Test this, and see what are you missing :)
Try with something like this. In this case I'm saving an image!
For creating the directory:
File directory = new File(Environment.getExternalStorageDirectory()
+ File.separator + appName);
directory.mkdirs();
And for saving into it
public void save(Bitmap graph, Context context, String name, String time, boolean now) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
graph.compress(Bitmap.CompressFormat.PNG, 100, bytes);
// you can create a new file name "test.jpg" in sdcard folder.
String fileName = "";
if (now){
fileName = getDateTime()+"_00"+".png";
}
else {
fileName = time.replace(".txt", ".png");
}
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "appName/" + fileName);
f.createNewFile(); // write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
}
I think the trick is in File.separator!

Android create folders in Internal memory issue

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.

Folder created instead of a file

I want to create a file in a defined directory, i tried this two codes but the first just creates folders and the other output an exception: no such file or directory:
First code:
File file = new File(Environment.getExternalStorageDirectory()
+File.separator
+"carbu"
+File.separator
+"install");
file.mkdir();
Then i added this code hopefully to create the file:
File file2 = new File("/carbu/install/","voitu");
file2.createNewFile();
Can anyone please try to help me ?
Thank you very much :).
Try this in your Activity:
FileOutputStream fos = openFileOutput(YOUR_FILE_NAME, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(5);
oos.flush();
This will create file if it isn't exist. Of course you should close oos and fos.
Here is the most simple solution, working at 100% ;)
File dir = new File (sdCard.getAbsolutePath() + "/jetpack/install");
dir.mkdirs();
File file = new File(dir, "wipe");
have you tried:
File f=new File("myfile.txt");
if(!f.exists())
{
f.createNewFile();
}
In you example you are only giving the pathname to the file but you are not defining the type and the name of the new file.
http://download.oracle.com/javase/6/docs/api/java/io/File.html
Also try following:
String FILENAME = "/carbu/install/test.txt";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close()
got the above example from: http://developer.android.com/guide/topics/data/data-storage.html
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.gpx");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
} catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
}
While you were careful in constructing the path correctly in the first segment, you just hard-coded the wrong path in the second part. Ensure you use the correct path, possibly as follows:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()
+File.separator
+"carbu"
+File.separator
+"install";
File file = new File(path);
file.mkdir();
File file2 = new File(path + File.separator + "voitu");
file2.createNewFile();

Categories

Resources