Can't create a file - android

I'm trying to create a simple image file on Android and have the two following methods:
Creating the directory:
private void createThumbnailDir() {
File file = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + "scouthouse",
"scouthouse_thumbnails");
this.getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
if (!file.mkdirs()) {
Log.d("file", "file not created");
}
}
Creating the file:
private File createNewThumbnailFile() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss",
Locale.ENGLISH);
Date date = Calendar.getInstance().getTime();
File file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"scouthouse" + File.separator + "schouthouse_thumbnails" + File.separator
+ sdf.format(date) + ".jpg");
try {
if (file.createNewFile()) {
return file;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
When I create the file the following IOException is raised:
java.io.IOException: ENOENT (No such file or directory)
But the directory does exist when I check the file manager on my phone.
Edit:
More about the error:
stacktrace = null, so I only have the cause and the detailmessage, and they're both the same: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)

Do you have this on your manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
?
EDIT:
private File createThumbnailDir() {
File file = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + "scouthouse",
"scouthouse_thumbnails");
this.getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
if (!file.mkdirs()) {
Log.d("file", "file not created");
return file;
}else {return null}
}
Now:
private File createNewThumbnailFile() {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss",
Locale.ENGLISH);
Date date = Calendar.getInstance().getTime();
String filename= sdf.format(date) + ".jpg";
File file = new File(createThumbnailDir(), filename);
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(AndroidWebImage.this, "Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidWebImage.this, e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(AndroidWebImage.this, e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
reference

Have you tried saving your file somewhere else? Your app might have no write permission.

Related

How to save image to pictures folder in android

I want to save image to Pictures folder in android. I do not have any external memory card attached.
Code:
String ImageDirectory = "QrCode";
#RequiresApi(api = Build.VERSION_CODES.N)
public void saveImage(Bitmap myBitmap, String busNumber, String imageName, EditText imagePath) {
String IMAGE_DIRECTORY = "QRCode";
try (ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY+ "/" + busNumber );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
Log.d("dirrrrrr", "" + wallpaperDirectory.mkdirs());
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, imageName + ".jpeg");
imagePath.setText("Sandeep");
f.createNewFile(); //give read write permission
imagePath.setText("Chintu");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
imagePath.setText("f.getAbsolutePath()");
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
Toast.makeText(getBaseContext(), f.getAbsolutePath(), Toast.LENGTH_SHORT).show();
//return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
//imagePath.setText("Pintu");
}
} catch (IOException e) {
e.printStackTrace();
}
}
imagePath.setText("Sandeep"); is executed. But imagePath.setText("Chintu"); is not executed. So, it throws exception at f.createNewFile(); catch block is executed and imagePath.setText("Pintu"); is executed
manifestfile:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You are using wroing picture directory. The path of Picture directory:
File pictureDir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(pictureDir, "ImageName.jpg");

Write a string to a file

I want to write something to a file. I found this code:
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The code seems very logical, but I can't find the config.txt file in my phone.
How can I retrieve that file which includes the string?
Not having specified a path, your file will be saved in your app space (/data/data/your.app.name/).
Therefore, you better save your file onto an external storage (which is not necessarily the SD card, it can be the default storage).
You might want to dig into the subject, by reading the official docs
In synthesis:
Add this permission to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
It includes the READ permission, so no need to specify it too.
Save the file in a location you specify (this is taken from my live cod, so I'm sure it works):
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path =
Environment.getExternalStoragePublicDirectory
(
//Environment.DIRECTORY_PICTURES
Environment.DIRECTORY_DCIM + "/YourFolder/"
);
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
[EDIT] OK Try like this (different path - a folder on the external storage):
String path =
Environment.getExternalStorageDirectory() + File.separator + "yourFolder";
// Create the folder.
File folder = new File(path);
folder.mkdirs();
// Create the file.
File file = new File(folder, "config.txt");
Write one text file simplified:
private void writeToFile(String content) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.flush();
writer.close();
} catch (IOException e) {
}
}
This Method takes File name & data String as Input and dumps them in a folder on SD card.
You can change Name of the folder if you want.
The return type is Boolean depending upon Success or failure of the FileOperation.
Important Note: Try to do it in Async Task as FIle IO make cause ANR on Main Thread.
public boolean writeToFile(String dataToWrite, String fileName) {
String directoryPath =
Environment.getExternalStorageDirectory()
+ File.separator
+ "LOGS"
+ File.separator;
Log.d(TAG, "Dumping " + fileName +" At : "+directoryPath);
// Create the fileDirectory.
File fileDirectory = new File(directoryPath);
// Make sure the directoryPath directory exists.
if (!fileDirectory.exists()) {
// Make it, if it doesn't exist
if (fileDirectory.mkdirs()) {
// Created DIR
Log.i(TAG, "Log Directory Created Trying to Dump Logs");
} else {
// FAILED
Log.e(TAG, "Error: Failed to Create Log Directory");
return false;
}
} else {
Log.i(TAG, "Log Directory Exist Trying to Dump Logs");
}
try {
// Create FIle Objec which I need to write
File fileToWrite = new File(directoryPath, fileName + ".txt");
// ry to create FIle on card
if (fileToWrite.createNewFile()) {
//Create a stream to file path
FileOutputStream outPutStream = new FileOutputStream(fileToWrite);
//Create Writer to write STream to file Path
OutputStreamWriter outPutStreamWriter = new OutputStreamWriter(outPutStream);
// Stream Byte Data to the file
outPutStreamWriter.append(dataToWrite);
//Close Writer
outPutStreamWriter.close();
//Clear Stream
outPutStream.flush();
//Terminate STream
outPutStream.close();
return true;
} else {
Log.e(TAG, "Error: Failed to Create Log File");
return false;
}
} catch (IOException e) {
Log.e("Exception", "Error: File write failed: " + e.toString());
e.fillInStackTrace();
return false;
}
}
You can write complete data in logData in File
The File will be create in Downlaods Directory
This is only for Api 28 and lower .
This will not work on Api 29 and higer
#TargetApi(Build.VERSION_CODES.P)
public static File createPrivateFile(String logData) {
String fileName = "/Abc.txt";
File directory = new File(Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DOWNLOADS + "/");
directory.mkdir();
File file = new File(directory + fileName);
FileOutputStream fos = null;
try {
if (file.exists()) {
file.delete();
}
file = new File(getAppDir() + fileName);
file.createNewFile();
fos = new FileOutputStream(file);
fos.write(logData.getBytes());
fos.flush();
fos.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

unable to write and append the text file android

I am trying to write a text file for logging in my app. When it comes to execution, there are READ-ONLY EXCEPTION and hence cannot write the text file.
only file 1" can be executed
Now using 5.0.1
The below is my code :
public static void writefile(String text )
{
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download" );
String fileName= date() + ".txt" ;
File dir = new File(externalStorageDir , File.separator + "eyedebug" );
boolean statement = dir.exists() && dir.isDirectory();
if(!statement) {
// do something here
dir.mkdirs();
System.out.println("file 1");
}
File myFile = new File(dir.getAbsolutePath() , File.separator + fileName );
if(!myFile.exists()){
try {
myFile.createNewFile();
System.out.println("file 2");
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fileWritter = new FileWriter(myFile.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(text);
bufferWritter.newLine();
System.out.println("file 3");
bufferWritter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
after long work finally i found your solution, just implement below code it will help you..
public static void writefile(String text )
{
File externalStorageDir = new File (Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/eyedebug/" );
String fileName= System.currentTimeMillis() + ".txt" ;
boolean statement = externalStorageDir.exists() && externalStorageDir.isDirectory();
if(!statement) {
// do something here
externalStorageDir.mkdirs();
System.out.println("file 1");
}
File myFile = new File(externalStorageDir.getAbsolutePath() , fileName );
if(!myFile.exists()){
try {
myFile.createNewFile();
System.out.println("file 2");
}
catch (IOException e)
{
e.printStackTrace();
}
}
try
{
FileWriter fileWritter = new FileWriter(myFile,true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.append(text);
bufferWritter.newLine();
System.out.println("file 3");
bufferWritter.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
add write permission WRITE_EXTERNAL_STORAGE in your manifest file.
Add following lines in your manifest file
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
There are two ways to print application log into a file.
If you want to get all loged events then you can use following method that used command line to save logs into file.
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time -d *:V";
Log.d("FB Error Log", "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
else you can use following method to save indivisual logs into file.
public static void appendLog(String text) {
File logFile = new File("sdcard/app_log.txt");
try {
if (!logFile.exists()) {
logFile.createNewFile();
}
//BufferedWriter for performance, true to set append to file flag
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String format = "[dd/MM/yy HH:mm:ss]";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
String currentTime = sdf.format(date);
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(currentTime+" - "+text);
buf.newLine();
buf.close();
}
catch (Exception e) {
Log.e("StaticUtils", e.getMessage(), e);
}
}
Dont forget to add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android Save the image in sdcard

I am saving an image into sdcard, but I want that the directory folder will be automatically shown in the gallery and the image on the folder. Whenever I save the image I am rebooting my phone for the directory folder to be shown in the gallery. Is it my code that has a problem? or the phone? Please help me. Thank you so much. I dont know what to do
here's my code:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
mTempDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + "PixiePhotos" + "/";
prepareDirectory();
save.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ShowToast")
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v(TAG, "Save Tab Clicked");
viewBitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(viewBitmap);
tapimageview.draw(canvas);
canvas.drawBitmap(bp, 0, 0, paint);
canvas.drawBitmap(drawingBitmap, matrix, paint);
canvas.drawBitmap(bmpstickers, matrix, paint);
//tapimageview.setImageBitmap(mBitmapDrawable.getBitmap());
try {
mBitmapDrawable = new BitmapDrawable(viewBitmap);
mCurrent = "PXD_" + new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date()) + ".jpg";
bp1 = mBitmapDrawable.getBitmap();
tapimageview.setImageBitmap(bp1);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.JPEG, 100, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
Toast.makeText(getApplicationContext(), "Your photo has been saved", Toast.LENGTH_LONG).show();
}
});
}
private boolean prepareDirectory() {
try {
if (makeDirectory()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(this, getString(R.string.sdcard_error), 1000).show();
return false;
}
}
private boolean makeDirectory() {
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
if (mTempFile.isDirectory()) {
File[] mFiles = mTempFile.listFiles();
for (File mEveryFile : mFiles) {
if (!mEveryFile.delete()) {
//System.out.println(getString(R.string.failed_to_delete) + mEveryFile);
}
}
}
return (mTempFile.isDirectory());
}
Try this:
private boolean storeImage(Bitmap imageData, String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/myAppDir/myImages/"
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(CompressFormat.PNG, 100, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
Don't forget to add Storage Permissions
Since this is operation that saves data on external memory, it requires AndroidManifest.xml permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
try it out
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
String fname = "Image.jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and add permission in your maniefest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem is not with the code ...
what happens over here is
After downloading the file on the sdcard the gallery is not notified with new file added or downloaded to the system
What you need to do is you have to manually Notify the gallery that ...okhay gallery file is added please show ..:)
For that you have to use MediaScannerConnection
Download the file ,scan the particular file and it will be shown in the gallery
and you are done:)

Create a .nonmedia File in Android doesnt work

My App creates and use some images from the sd-card.
These images are shown in the gallery of the device, but i dont want that.
So i tried to create a .nonmedia file in this directory, but my problem is that this file wont be created.
Heres the code:
public void createNonmediaFile(){
String text = "NONEMEDIA";
String path = Environment.getExternalStorageDirectory().getPath() + "/" + AVATARS + "/.nonmedia";
FileOutputStream fos;
try {
fos = new FileOutputStream(path);
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
There are no exceptions.
I gues it has something to do with the "." in the name. If i try the same whithout it, the file gets created.
Thanks for your help.
Try using the following example
File file = new File(directoryPath, ".nomedia");
if (!file.exists()) {
try {
file.createNewFile();
}
catch(IOException e) {
}
}
Put below permission in your android-manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And then below code should work just fine:
private static final String AVATARS = "avatars";
public void createNonmediaFile(){
String text = "NONEMEDIA";
String path = Environment.getExternalStorageDirectory().getPath() + "/" + AVATARS + "/.nonmedia";
String f = Environment.getExternalStorageDirectory().getPath() + "/" + AVATARS ;
FileOutputStream fos;
try {
File folder = new File(f);
boolean success=false;
if (!folder.exists()) {
success = folder.mkdir();
}
if (true==success) {
File yourFile = new File(path);
if(!yourFile.exists()) {
yourFile.createNewFile();
}
} else {
// Do something else on failure
}
fos = new FileOutputStream(path);
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources