can't create folder on externalstorage - android

I'm trying to create a folder on external storage with no success.Although i've managed to create a folder in my app's directory, i can't do the same for external storage and i also get false when i call canWrite().I have declared the WRITE_EXTERNAL_PERMISSION on manifest.
Here is my code for my app's directory
File file1=new File(context.getFilesDir(), "//test1");
file1.mkdir();
System.out.println(file1.canWrite());
and for ExternalStorage respectively
File file2=new File(Environment.getExternalStorageDirectory(), "//test2");
file2.mkdir();
System.out.println(file2.canWrite());
In the first case the folder gets created and i get true on println.On the second one folder does not get created and i get false on println.

Add Below Permission i your manifest.xml
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
String PATH = Environment.getExternalStorageDirectory() + "/download/YourPath";
String fileName="Name for your File";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();

This will create a directory,if you use comma,it means "//test2" will become a file name
String string = Environment.getExternalStorageDirectory().getPath() + "/test2";
File file = new File(string, "file_name");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(your_data);
fileOutputStream.flush();
fileOutputStream.close();

Related

Where is located the APK file for download in android?

I'm currently developing an app that need to check if there is a new version available.
I found how to download the apk and install it.
But i cant figure out how to get the APK URL.
I'm using the testing (alpha) environment, so my app is not published yet, where can i get the APK URL.
Here's the code for download:
try {
URL url = new URL(apkurl);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "app.apk");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();//till here, it works fine - .apk is download to my sdcard in download file
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
}
How can i get the APK URL?
you have to create it yourself. create folder and name a file to it. as you are doing in the code. like
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "app.apk");
to create your own one do this.
Add this permission in Manifest,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and to create folder with name of your file
File folder = new File(context.getCacheDir().getPath() + "/files/myFolder");
folder.mkdirs();
File f= new File(folder, "app.apk");
if (!folder .exists()){
folder.create();
}
where you can put your apk
If you are using Alpha (testing) environment. This is the Url:
https://play.google.com/apps/testing/com.yourdomain.package
But, your APK will not be available to public, it is ONLY for activated testers in the alpha section.

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

Playing video from app cache dir

Can anyone explain why downloading/playing a video from my applications cache directory does not work, but downloading/playing the same video from my sdcard does work?
Note: this video is being downloaded. I am saving to memory before calling VideoView.setVideoPath(...).
// Works
File file = new File(Environment.getExternalStorageDirectory(), "vid-test.3gp");
// Does not work
File file = new File(getCacheDir(), "vid-test.3gp");
In each case the file in question does exist.
If I attempt to call VideoView.setVideoURI(...) and "stream" the video to my VideoView, it is hit and miss whether or not it will work.
Can anyone explain this behavior?
It's probably a permission issue. Here is a working snipped:
InputStream in = connection.getInputStream();
File file = new File(getApplicationContext().getCacheDir() ,fileName);
if(!file.exists()){
file.setReadable(true);
file.createNewFile();
if (file.canWrite()){
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = in.read(buffer)) > 0 ) {
out.write(buffer,0, len1);
}
out.close();
}
in.close();
Runtime.getRuntime().exec("chmod 755 "+getCacheDir() +"/"+ fileName);
}

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