Folder created instead of a file - android

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

Related

Where I can find the stored files in my phone?

my app save files in folder Documents. But I can't find this files in my telephone. What the problem?
File file = new File(getFilesDir() + DIR_NAME + fileName + ".txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
}
fos = new FileOutputStream(file);
osw = new OutputStreamWriter(fos, "UTF-8");
osw.write(editText.getText().toString());
File cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "folder-name"+"file-name");
//for make the directory if not exist
if (!cacheDir.exists())
//check file and other code...
android.os.Environment.getExternalStorageDirectory()
is used to check files in phone internal memory.

How to create folder in internal memory

This is my application memory path /data/data/com.myexample.folder/files and it works fine but when I create a new directory like this /data/data/com.myexample.folder/files/photos,
it is not created and I wonder what's wrong? How do I create a new folder inside application.
public void loadFeed();
String file paths="data/data/com.myapplication.myfolder/files";
File outputFiles= new file(filePaths);
File files1=outputFile1.listFiles();
For your own directory in file storage:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
For saving in sub directory inandroid public folders say DCIM:
use File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Mainly, make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Call openFileOutput() with the name of the file and the operating mode.
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
just use this way:
public void createFile(Context c) throws IOException{
String FILENAME = timeStamp();
String string = "hello world!";
FileOutputStream fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}

How do i save an image in external storage gallery in android

I'm trying to write an image file into the public gallery folder in a specific directory but I keep getting an error that I can't open the file because its a directory.
What I have so far is the following
//set the file path
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
File outputFile = new File(path,"testing.png");
outputFile.mkdirs();
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Where directory is the application name. So all the photos saved by the application will go into that folder/directory, but I keep getting the error
/storage/sdcard0/Pictures/appname/testing.png: open failed: EISDIR (Is a directory)
Even if I don't try to put it in a directory and cast the variable path as a File like
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
I don't get the error however the photo is still not showing up in the gallery.
***Answer
The problem was that when I ran this code originally it created a DIRECTORY named testing.png because I failed to create the directory before creating the file IN the directory. So the solution is to make the directory first then write into it with a separate file like so
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + File.separator + directory;
//directory is a static string variable defined in the class
//make a file with the directory
File outputDir = new File(path);
//create dir if not there
if (!outputDir.exists()) {
outputDir.mkdir();
}
//make another file with the full path AND the image this time, resized is a static string
File outputFile = new File(path+File.separator+resized);
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Note you may need to go into your storage and manually delete the directory if you made the same mistake i did to begin with
You are trying to write into a directory instead of file.
try this
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
File outputDir= new File(path);
outputDir.mkdirs();
File newFile = new File(path + File.separator + "test.png");
FileOutputStream out = new FileOutputStream(newFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Your code is correct, only little changes needs as follows,
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + directory;
// First Create Directory
File outputFile = new File(path);
outputFile.mkdirs();
// Now Create File
outputFile = new File(path,"testing.png");
FileOutputStream out = new FileOutputStream(outputFile);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
Also don't forget to give WRITE_EXTERNAL_STORAGE permission in your AndroidManifest.xml file.
If you are getting this error while working on Android Emulator; you need to enable SD Card storage on the emulator.
public static String SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/FolderName");
if(!myDir.exists())
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".png";
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 (Throwable e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
getExternalStoragePublicDirectory is now deprecated and you should use
context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
Use this way :
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/mnt/sdcard/" + new Date().getTime() + ".jpg"));`
Path : Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + file name

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

Trying to save a file but getting "Parent directory of file does not exist" even after trying to create dir

I'm trying to save an image to my sdcard but running into the following error:
java.io.IOException: Parent directory of file does not exist: /sdcard/skdyImages/a46e2e08-9154-4fe7-96e8-2af0a7a92867.jpg
I do have the permissions in my manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Here is my code:
String newName = UUID.randomUUID().toString();
Bitmap bmp = ImageLoader.getInstance().getBitmap(e.getUrl());
File file = new File("/sdcard/skdyImages", newName + ".jpg");
file.getParentFile().mkdirs();
file.createNewFile();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
bmp.compress(CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Any ideas?
Try something like this...
// Automatically creates folder on sdcard called /Android/data/<package>/files
// if it doesn't exist
File ImageDir = new File(getExternalFilesDir(null).getAbsolutePath());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(ImageDir + "/" + newName + ".jpg"));

Categories

Resources