File not being created on android device - android

I'm trying to save strings to a text file in the external memory of the android device.
I call this method:
public void writeToFile(String name, String mevent)
{
File path =
Environment.getExternalStoragePublicDirectory
(
Environment.DIRECTORY_DOWNLOADS
);
if(!path.exists())
{
path.mkdirs();
}
File myfile = new File(path, "config.txt");
try
{
myfile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myfile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(name);
myOutWriter.append(mevent);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
I call the above method from an OnActivityResult that waits for strings from another activity. The strings definitely return from the other activity, but the file isn't created. I have given the write permission to external memory.
Any ideas to what I am doing wrong?

Related

exception while using OuputStreamWriter

when using OutputStreamWriter, while I try to make multiple directories (depending on a function result) and writing strings into the files, I have an exception.
Why does my program keep jumping to exception and saveFile() always return false?
private boolean saveFile() {
File card = Environment.getExternalStorageDirectory();
File dir = new File(card.getAbsolutePath() + choosePath());
if (!dir.exists()) {
dir.mkdir();// creates directory by the given pathname
}
File file = new File(dir, etFileName.getText().toString());
try {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(configString); // from character to byte
osw.flush();
osw.close();
return true;
} catch (IOException e) {
return false;
}
}
try this
private boolean saveFile() {
File card = Environment.getExternalStorageDirectory();
String fullPath = card.getAbsolutePath()
+ choosePath()
+ etFileName.getText().toString(); //I guess this should generate the fullPath, if i understood well your code
File file = new File(fullPath); //open the file
file.getParentFile().mkdirs(); //create parent dirs if necessary
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
try {
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write(configString); // from character to byte
osw.flush();
osw.close();
return true;
} catch (IOException e) {
return false;
}
}
EDIT 1: added "file.createNewFile()"
EDIT 2: be sure to have the right to write file. You should have this in you manifest file

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

How to set append mode to append content to a text file in android?

I use the following code to write text content to MessageCleanupLogs.txt, it seems that it's a overwrite mode, when I run the code again, the previously created MessageCleanupLogs.txt is overwrite.
How can I set append mode for the file MessageCleanupLogs.txt to append new content? Thanks!
String filename=Environment.getExternalStorageDirectory() + "/MessageCleanupLogs.txt";
try
{
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
String aa="a\r\nb\r\nb";
FileOutputStream fOut = new FileOutputStream(filename);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("test");
myOutWriter.append("\r\n");
myOutWriter.append(aa);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
The java methods of append itself will work.
PrintWriter out = null;
String filepath = "/sdcard/myfile.txt"; // your file path here
String contents = "hello world"; // your file contents here
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(filepath, true)));
out.println(contents);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Reference from https://stackoverflow.com/a/1625263/3894784

Android: Write text to txt

With the following code, I try to write to my sdcard:
public void writedata(String data) {
//BufferedWriter out = null;
System.out.println(data);
try{
FileOutputStream out = new FileOutputStream(new File("/sdcard/tsxt.txt"));
out.write(data.getBytes());
out.close();
} catch (Exception e) { //fehlende Permission oder sd an pc gemountet}
System.out.println("CCCCCCCCCCCCCCCCCCCCCCCALSKDJLAK");
}
}
The permission in the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
But now, when I open the file, nothing is in there. Where´s the problem? I´m sure data has some value.
EDIT:
I get this message in the LogCat:
02-06 01:59:51.676: W/System.err(1197): java.io.FileNotFoundException: /storage/sdcard0/sdcard/tsxt.txt: open failed: ENOENT (No such file or directory)
I tried to create the file on the sdcard but still the same error. Is there a code that the File is created if it doesn´t exists?
Try with this code:
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir");
File file = new File(dir, "tsxt.txt");
FileOutputStream f = new FileOutputStream(file);
So the path to the file is not correct. You should remove directory name:
File dir = new File (sdCard.getAbsolutePath() + "/");
Try this:
BufferedWriter out;
try {
FileWriter fileWriter= new FileWriter(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt")
out = new BufferedWriter(fileWriter);
out.write("Your text to write");
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try{
File myFile = new File("/sdcard/tsxt.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("your data here");
myOutWriter.close();
fOut.close();
}catch(Exception e){}
Try this
FileOutputStream fOut =openFileOutput(Environment.getExternalStorageDirectory().getPath()+"/tsxt.txt",MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
Before writing any file on sd card you need to check that is sdcard mounted or not, if not then just mount it and then write the file on it using external storage path.
you may use following code to check is sdcard mount or not
static public boolean hasStorage(boolean requireWriteAccess) {
//TODO: After fix the bug, add "if (VERBOSE)" before logging errors.
String state = Environment.getExternalStorageState();
Log.v(TAG, "storage state is " + state);
if (Environment.MEDIA_MOUNTED.equals(state)) {
if (requireWriteAccess) {
boolean writable = checkFsWritable();
Log.v(TAG, "storage writable is " + writable);
return writable;
} else {
return true;
}
} else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
if(hasStorage(true)){
//call here your writedata() function
}
This Code is working perfectly..
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStorageDirectory() + "/files", albumName);
Log.d("File", "Bug file Created" + file.getAbsolutePath());
return file;
}`
To write the textfile inside sd Card(/storage/sdcard0/files/bugReport.txt)
try{
outputStream = new FileOutputStream(this.getAlbumStorageDir(bugReport.txt));
outputStream.write(report.toString().getBytes());
Log.d("File","Report Generated");
outputStream.close();
}
catch(Exception e){
e.printStackTrace();
}

android: saving files to specific folder for later retrieval

I am working on a drawing part, and have written the following code to save the image to the designated camera folder. However, I would rather like to create a new folder using the app name and save the image to the folder. How could that be made?
I would also like to later on retrieve the image files from that specific folder too.
Thanks!
Current code:
String fileName = "ABC";
// create a ContentValues and configure new image's data
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, fileName);
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/jpg");
// get a Uri for the location to save the file
Uri uri = getContext().getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI, values);
try
{
OutputStream outStream = getContext().getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush(); // empty the buffer
outStream.close(); // close the stream
Try this it might help you.
public void saveImageToExternalStorage(Bitmap image) {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "image.png");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
// 100 means no compression, the lower you go, the stronger the compression
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
This Method works after so many try.
private String getFilename() {
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".mp3");
}

Categories

Resources