Create a .nonmedia File in Android doesnt work - android

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

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

Android Create zip file

I am using this piece of code to create a zip file:
String filename = Helper.Timestamp() + ".zip";
ZipOutputStream out = Helper.CreateZipOutputStream(filename);
Helper.AddZipFolder(out, Helper.ImageFolder);
Helper.AddZipFile(out, new File(Settings.FILENAME));
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Helper functions:
public static String Timestamp() { return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); }
public static ZipOutputStream CreateZipOutputStream(String filename){
FileOutputStream dest = null;
try {
dest = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return new ZipOutputStream(new BufferedOutputStream(dest));
}
public static void AddZipFolder(ZipOutputStream out, File folder){
for (File file: folder.listFiles()){
Helper.AddZipFile(out, file, folder.getName() + File.separator + file.getName());
}
}
public static void AddZipFile(ZipOutputStream out, File file){
AddZipFile(out, file, file.getName());
}
public static void AddZipFile(ZipOutputStream out, File file, String path){
byte[] data = new byte[1024];
FileInputStream in;
try {
in = new FileInputStream(file);
} catch (FileNotFoundException e) {
return;
}
try {
out.putNextEntry(new ZipEntry(path));
int len;
while ((len = in.read(data)) > 0)
out.write(data, 0, len);
out.closeEntry();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
However there seems to be something wrong with the out.write(data, 0, len); because there is a NullPointerException inside this function call. I believe this is due to the fact that my CreateZipOutputStream throws a FileNotFoundException.
So how should I properly create a zip file?
Because you forget to append base path on your filename. your filename must be like:
String filename = Environment.getExternalStorageDirectory().getPath() + "/" + Helper.Timestamp() + ".zip";

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;
}

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:)

writing/returning a HTML String to file to internal file directory android

Hi i have a string that contains html and css that i want to load into a WebView as a file. so i want to create a Directory on the internal storage i don't really want to store it on an SDCard as the file i'm saving contains important information. I then want to create a mFile.html not that directory. And the final step is then return the file to load into a WebView. Does anyone know how to do this?
heres what i have tried so far
public static void writeFileToDirectory(Context activityContext, String writableString,String folderName, String fileName){
File myDir = activityContext.getFilesDir();
try {
File secondFile = new File(myDir + "/" + folderName + "/", fileName);
if (secondFile.getParentFile().mkdirs()) {
secondFile.createNewFile();
FileOutputStream fos = new FileOutputStream(secondFile);
fos.write(writableString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File secondInputFile = new File(myDir + "/html/", fileName);
InputStream secondInputStream = new BufferedInputStream(new FileInputStream(secondInputFile));
BufferedReader r = new BufferedReader(new InputStreamReader(secondInputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
secondInputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
try this
File myDir = activityContext.getFilesDir();
try {
File secondFile = new File(myDir + "/" + folderName);
if(!secondFile.exists())
{
secondFile.mkdir();
}
FileOutputStream fos = new FileOutputStream(secondFile.getAbsolutePath()+"/"+fileaName);
fos.write(writableString.getBytes());
fos.flush();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources