unable to write and append the text file android - 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" />

Related

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 saving log file as hidden files

There is a problem with access to file via Windows Explorer. My files are saved on non root device. I can see them only using embedded file manager installe on Android Device, but there is problem with looking them with Windows Explorer. I plug-in and plug-out my device, but it doesn't work good. Here is my code:
public class LoggerUtil {
private File sdRoot;
private String dir;
private File workingDirectory;
private File log;
private Context applicationContext = MApp.getContext();
public LoggerUtil() {
}
#SuppressLint("SimpleDateFormat")
public File createNewLogFile() {
String currentDateandTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
String path = sdRoot.toString() + dir + "log" + currentDateandTime + ".txt";
return new File(path);
}
#SuppressLint("SimpleDateFormat")
public void appendLog(String text) {
sdRoot = Environment.getExternalStorageDirectory();
dir = "/Android/data/" + applicationContext.getPackageName() + "/log/";
workingDirectory = new File(sdRoot, dir);
workingDirectory.mkdirs();
log = createNewLogFile();
if (ABC.isOK()) {
File logFile = log;
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
// BufferedWriter for performance, true to set append to file
// flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(currentDateandTime + " " + text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My execution is:
LoggerUtil loger = new LoggerUtil();
loger.appendLog("TEST");

Can't create a file

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.

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

Create log file on SendSms and Receive SMS

I am working on an Android version 2.3.3 application which depends on SMS for SMS dealing. I have written two classes SendSMS and ReceiveSMS. I want to create a log file which logs each SMS that it is sent or received. For creating log file I have written code but does not work.
Following is my code,
public void WriteOnLog()
{
File exportDir = Environment.getExternalStorageDirectory();
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" msg";
}
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
txt = dt + " |" +" Send " + "| " + phoneNumber + " | " + message.toUpperCase();
out.write(txt + "\n");
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
I have used the OutputStreamWriter (instead of FileWriter) Approach. I have it working in my dev environment and tested on device (android 2.3.6). try this out:
try {
File directory;
if(isSDCard){
directory = new File(Environment.getExternalStorageDirectory().toString()+"/"+folderNameOrPath+"/");
}
else{
directory = new File(folderNameOrPath);
}
boolean fileReturnVal = directory.mkdirs();
if(fileReturnVal){
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder Created successfully");
}
else{
Log.d("Storage", "Write in SD Card: " + folderNameOrPath + " folder either already exists or creation failed");
}
File file = new File(directory, fileNameWithExtention);
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//Write the string to the file
osw.write(text);
osw.flush();
osw.close();
//file saved
Toast.makeText(context, "Text saved in SD Card", Toast.LENGTH_SHORT).show();
return true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: File Not Found ERROR: " + e.toString());
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Storage", "Write in SD Card: IOException ERROR: " + e.toString());
return false;
} catch (Exception e) {
Log.e("Storage", "Write in SD Card: ERROR: " + e.toString());
return false;
}
you can set append mode for you task. The variables isSDCard, folderName, fileNameWithExtn. etc. are method level variables. I am passing those as parameters.

Categories

Resources