In my app I am trying to create a file and write to it.
This is my code:
try {
File tmpDir = new File("/sdcard/LivingstoneTemp/");
tmpDir.mkdirs();
String filename = "Livingstone_" +UUID.randomUUID() + ".html";
File outputFile = new File(tmpDir, filename);
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] data = response.getBytes();
fos.write(data);
fos.flush();
fos.close();
} catch (Exception e) {
Log.i("LivingstoneInfo", "Error: " + e.getMessage());
}
Permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
I get a "No such file or directory" exception.
I'm running this on a Nexus 5 with an internal storage.
Related
I'm working on an Android project and i wanna get the path of the uploaded picture from Camera or Gallery. All the permissions are set and I use this function to get the path but it seems createNewFile() is always ignored and i get path="" all the time.
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
but i get a problem on the log
There could be something the way you put together your filepath, but this is not viewable by your post. You could have missed giving permissions in the manifest, so the file is not created.
Try this:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Make sure you have an External SD card in your phone as you are trying to access
Environment.getExternalStorageDirectory()
I am having one heck of a time with this new permission request in Android 6. My app worked fine, and then in the last two days it is force closing all the time. If I change the target SDK level to 22, it works fine, but of course Play Store wont let you downgrade the SDK.
I need these permissions.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.android.vending.BILLING" />
After this I am not sure how to work the requesting, or new way of implementing the permissions part so the errors will stop. I have been working on this for hours and have googled and search endlessly. While alot of examples out there all tell me to do the same thing, I just cannot seem to get it write in Android Studio. Any help would be greatly appreciated.
Here is part of the code that was giving me issues.
public void exportSkin(View arg0) throws IOException {
if (type.equals("popular")) {
AssetManager assetManager = getAssets();
InputStream is = assetManager.open("skins/" + skinname + ".png");
// create a File object for the parent directory
File wallpaperDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() + "/SkinYourself/");
// have the object build the directory structure, if needed.
//noinspection ResultOfMethodCallIgnored
wallpaperDirectory.mkdirs();
// create a File object for the output file
File out = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/SkinYourself/", "" + PopChar.character_name + ".png");
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(out);
int read;
while ((read = is.read(buffer, 0, 1024)) >= 0) {
fos.write(buffer, 0, read);
}
fos.flush();
fos.close();
is.close();
}
if (type.equals("create")) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/SkinYourself");
myDir.mkdirs();
String fname = "SkinYourself" + System.currentTimeMillis() / 1000 + ".png";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
*/
Toast.makeText(MainActivity.this,
"Your skin has been saved to the SkinYourself folder check the info button on how to use it", Toast.LENGTH_LONG)
.show();
displayInterstitial();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))));
}
}
In android, how to write the file in the external directory in the desired folder.
i have use the following coding, but it doesn't seems to work.
File r = Environment.getExternalStorageDirectory();
File oD = new File(root.getAbsolutePath() + File.separator + "web_dir");
if (!outDir.isDirectory()) {
outDir.mkdir();
}
try {
if (!outDir.isDirectory()) {
throw new IOException(
"Unable to create directory");
}
File outputFile = new File(outDir, "web_file");
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
writer.write(new String("hello"));
Toast.makeText(context.getApplicationContext(),
"Successfully saved to: " + outputFile.getAbsolutePath(),
Toast.LENGTH_LONG).show();
writer.close();
} catch (IOException e) {
Log.w("et", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external"
+"storage.", Toast.LENGTH_LONG).show();
}
First make sure you have permission in your manifest file to write external storage.
<!-- Depends on your requirements -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ref: Saving Files - Android Developer Doc
below is the sample code to write file to external storage.
private void writeToSDFile(){
// Find the root of the external storage.
// See http://developer.android.com/guide/topics/data/data- storage.html#filesExternal
File root = android.os.Environment.getExternalStorageDirectory();
tv.append("\nExternal file system root: "+root);
// See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "myData.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println("Hi , How are you");
pw.println("Hello");
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i(TAG, "******* File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
} catch (IOException e) {
e.printStackTrace();
}
tv.append("\n\nFile written to "+file);
}
Hope it will help you..
What's the error message? As Mike said, your are probably missing the correct permission. Add the following to your manifest, as a child of the <manifest> tag:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well, I tried a lot of things, but the better goal that I achieve is copy the desired file to sd, but the new file size is 0bytes always :(
This is my code :
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = sonidoActual+".mp3";
File newSoundFile = new File(baseDir, fileName);
Uri mUri = Uri.parse("android.resource://com.genaut.ringtonelists/raw/"+sonidoActual);
AssetFileDescriptor soundFile;
try {
soundFile= getContentResolver().openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile=null;
}
try {
byte[] readData = new byte[1024*500];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
Log.d("Degug - While: ", "i: "+i);
}
fos.flush();
fos.close();
} catch (IOException io) {
}
Sorry for my bad english.Any one know the problem? Thanks a lot!
I have these permissions on my manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
More info:
I tried some code to copy files from assets and not work.. I have some app that set Ringtone well, so I don't think that my SD has a problem.. I feel hopeless :S
These are the code from assets, apparently works fine: https://stackoverflow.com/a/4530294/1422434
I tried too with getResources.openRawResource(): but not works
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = nombreActual+".mp3";
File newSoundFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024*500];
InputStream fis = getResources().openRawResource(contexto.getResources().getIdentifier(sonidoActual,"raw", contexto.getPackageName()));
FileOutputStream fos = new FileOutputStream(newSoundFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
As you are using the raw folder, simply use this from your activity:
getResources().openRawResource(resourceName)
I'm trying to display the path of the file by calling getAbsolutePath(), but the Application
displays nothing.
Java Code:
public void createExternalStorageDirectory() {
File file = new File(getExternalFilesDir(null), fileName);
try {
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
Toast.makeText(getBaseContext(), file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
is.close();
os.close();
} catch (IOException e) {
Log.w("ExternalStorage", " Error writing " + file, e);
}
}
Add the External File permission to the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And try using getApplicationContext() intead of getBaseContext()
you can try to use Environment.getExternalStorageDirectory() instead of getExternalFilesDir(null)