error when saving bitmap as image in android studio - java

I cant save the bitmap in my internal storage, when looking at the logcat, it says that "java.io.IOException: No such file or directory"
here is my code
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();
Log.d("hhhhh",wallpaperDirectory.toString());
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(MainActivity.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 "";
}
I didnt know what I'm doing wrong, help is much appreciated

Related

Android 10 does not save text file

I generated a text file and tried to save it. It doesn't work only on android Q. On android 9 , 8 and 7 it works. When I check if file exists on android 10 it works but I don't it on device . I do this :
private void createFile(Context ctx, String fileName, String text) {
File filesDir = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
filesDir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
}
assert filesDir != null;
if (!filesDir.exists()){
if(filesDir.mkdirs()){
}
}
File file = new File(filesDir, fileName + ".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
throw new IOException("Cant able to create file");
}
}
OutputStream os = new FileOutputStream(file);
byte[] data = text.getBytes();
os.write(data);
os.flush();
os.close();
Log.e("TAG", "File Path= " + file.toString());
if(file.exists()){
Log.e("d","d");
}
File fileTemp = new File(file.getPath());
FileInputStream notes_xml = new FileInputStream(fileTemp);
byte fileContent[] = new byte[(int)notes_xml.available()];
//The information will be content on the buffer.
notes_xml.read(fileContent);
String strContent = new String(fileContent);
Log.e("content",strContent);
notes_xml.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Android: File written in external storage is not showing

I'm trying to write a text file and save it in the android external storage, but file is not showing and I don't get any errors.
Here is my code:
String r;
String fname= "readme.txt";
r = Environment.getExternalStorageDirectory().toString();
File myDir = new File(r);
if (!myDir.exists()) {
myDir.mkdirs();
}
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
Out.write(wfile)
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Try something below. You can add validations to check whether file exists or not, as you please.
File file = new
File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "readme.txt");
FileOutputStream out = new FileOutputStream(file);
out.write(wfile);
out.flush();
out.close();
MediaScannerConnection.scanFile(mContext, new String[] { file.toString() }, null,new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
Just FYI, Environment.DIRECTORY_DOCUMENTS may does not exists in older android versions. Then you may have to add a validation to check that and create a directory if not.

How to decode base64 string and convert it into PDF/JPG and save it in storage

I would like to decode a base64 string and turn it into a file (as PDF/JPG) and save it to device, how for example in (/storage/emulated/0/Download/file.pdf).
For encode a file I use this code:
File originalFile = new File("/mnt/sdcard/download/file.pdf");
String encodedBase64 = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
byte[] bytes = new byte[(int) originalFile.length()];
fileInputStreamReader.read(bytes);
encodedBase64=Base64.encodeToString(bytes,Base64.NO_WRAP);
messaggio=encodedBase64.toString();
//encodedBase64 = new String(Base64.encode(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Now, I would like to decode this base64 string and convert it into a file and save it on the device.
You can try this:
FileOutputStream fos = new FileOutputStream(filepath);
fos.write(Base64.decode(base64String, Base64.NO_WRAP));
fos.close();
Where:
filepath: Path to the new file
base64String: Your base64 string that you want to convert
Give READ_STORAGE and Write_STORAGE Permission in Manifest and dont forget for RunTime Permission.
public static void storetoPdfandOpen(Context context, String base) {
String root = Environment.getExternalStorageDirectory().toString();
Log.d("ResponseEnv",root);
File myDir = new File(root + "/WorkBox");
if (!myDir.exists()) {
myDir.mkdirs();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Attachments-" + n + ".pdf";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
byte[] pdfAsBytes = Base64.decode(base, 0);
out.write(pdfAsBytes);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
File dir = new File(Environment.getExternalStorageDirectory(), "WorkBox");
File imgFile = new File(dir, fname);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (Build.VERSION.SDK_INT < 24) {
uri = Uri.fromFile(file);
} else {
uri = Uri.parse("file://" + imgFile); // My work-around for new SDKs, causes ActivityNotFoundException in API 10.
}
sendIntent.setDataAndType(uri, "application/pdf");
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(sendIntent);
}

Writing a text file to android storage for viewing later

So I'm trying to basically write some logs to a text file so i can view it later. I'm running this on a physical phone, not the emulator. I've tried so many different variations, and the most i got was it writing to data/data and storage/emulated but i can never access my file. Any help would be appreciated. Some of my latest undeleted examples have been:
String filename = "myfile.txt";
try {
File path = new File(context.getFilesDir(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
and
final String appPath = String.format("%s/Datafiles",
context.getFilesDir());
File path = new File(appPath);
if (!path.exists()) {
path.mkdir();
}
String fileName = String.format("%s/filedemo.txt", appPath);
and
try {
String filename = "myfile.txt";
File path = new File(Environment.getRootDirectory(), "myfolder");
if (!path.exists())
path.mkdir();
File output = new File(path, filename);
BufferedWriter buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
Log.d("Success",
"Successfully wrote a file " + context.getFilesDir());
} catch (Exception e) {
e.printStackTrace();
}
Both of the following put it under /storage/emulated/0/Android/data/com.example.simplelte/files/system/stuff/test.txt
and
/storage/emulated/0/Android/data/com.example.simplelte/files/storage/emulated/0/stuff/test.txt
respectively
try {
File file = new File(context.getExternalFilesDir(Environment
.getRootDirectory().getCanonicalPath()), "stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and
try {
File file = new File(context.getExternalFilesDir(Environment
.getExternalStorageDirectory().getCanonicalPath()),
"stuff");
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
File output = new File(file, "test.txt");
BufferedWriter buff;
buff = new BufferedWriter(new FileWriter(output));
buff.append("hi");
buff.close();
Log.d("Success", output.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and much more. I've followed every example I can think of. I literally just want to view the text file under Computer\Nexus 5\Internal storage\ I'm just a simple man with simple desires. Why does this have to be so complicated.
Have you tried this ?
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/");
File file = new File(dir, "text.txt");
FileOutputStream f = new FileOutputStream(file);

Resolving the issue: Illegal characters in path

I am developing an application that takes an XML file and an attachment to be sent to the following path. This path is for a fax appliance.
I keep getting this error message:
Problem processing drop file "\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml": Illegal characters in path.
The XML file and the attachment are both being created but not processed.
public class TestSender {
public static void main(String[] args) {
String outBox = "\\\\faxaux\\Fax_Drop\\Outbox";
String filename = "FaxDrop" + ".xml";
String filepath = outBox + "\\" + filename;
Writer writer = null;
try {
BufferedImage image;
URL url = new URL("http://colsolgrp.com/phone/jpg/fax8.jpg");
image = ImageIO.read(url);
//File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\AttachmentFolder\\attachment.jpg");
File newImage = new File("\\\\faxaux\\Fax_Drop\\Outbox\\FaxDrop\\FaxDropImage.jpg");
newImage.mkdirs();
newImage.createNewFile();
ImageIO.write(image, "jpg",newImage);
System.out.println("File has been written");
}
catch(Exception e) {
System.out.println("Could not create file");
}
try {
File f = new File(filepath);
f.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(f);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
writer = new BufferedWriter(outputStreamWriter);
// Create XML file here
}
catch (Throwable ex) {
ex.printStackTrace();
}
finally {
try {
writer.close();
}
catch (Exception ex) {
// Do nothing.
}
}
System.out.println("Success");
Try this:
URI u = new URI(URLEncoder.encode("\\co1-aux01prd01.tampa.healthe\Fax_Drop\Outbox\FaxDropSample1.xml"));

Categories

Resources