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.
Related
Now I copy mp4 file from external storage folder and save copy file in gallery with folder. But My gallery app doesn't have folder I code. Surely, File too. But In File Browser, There are exists correctly in DCIM folder.
So, How can I save file in gallery with folder that I code. Please let me know If you can solve this issue.
private void saveToGallery(String recVideoPath) {
progressdialog = new CNetProgressdialog(this);
progressdialog.show();
String folderName = "DuetStar";
String fromPath = recVideoPath;
String toPath = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM;
File toPathDir = new File(toPath + "/" + folderName);
final File fromPathFile = new File(fromPath);
File toPathFile = new File(toPath + "/" + folderName, recVideoPath.substring(recVideoPath.lastIndexOf("/") + 1, recVideoPath.length()));
Log.d(TAG, "saveToGallery: " + RecordActivity.currentCreateFileName);
Log.d(TAG, "saveToGallery: " + toPathDir.toString());
Log.d(TAG, "saveToGallery: " + fromPath.toString());
Log.d(TAG, "saveToGallery: " + toPath.toString());
if (!toPathDir.exists()) {
toPathDir.mkdir();
} else {
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
if (toPathDir.exists()) {
fis = new FileInputStream(fromPathFile);
fos = new FileOutputStream(toPathFile);
byte[] byteArray = new byte[1024];
int readInt = 0;
while ((readInt = fis.read(byteArray)) > 0) {
fos.write(byteArray, 0, readInt);
}
Log.d(TAG, "saveToGallery: " + readInt);
fis.close();
fos.close();
Log.d(TAG, "saveToGallery: " + "Seucceful");
} else {
Toast.makeText(this, "There is no directory", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.getMessage();
}
progressdialog.dismiss();
}
You can save in specific folder as you wish see this code snippet for idea
String extStorageDirectory;
extStorageDirectory = Environment.getExternalStorageDirectory().toString() + "/Video Folder name/";
//making the folder
new File(extStorageDirectory).mkdirs();
I am tring to create directory in External sdcard, I tested my code in MI (Android M), Samsung and in lenovo (Android L). Below code works fine in all devices except in lollipop.
private void crateDirectory() {
Log.d(TAG, "inside crateDirectory() ");
try {
String extPath = "";
String base = "/storage/sdcard1/"; //lenovo
// String base="/storage/9F44-E930/"; // for xiaomi
File baseFile = new File(base);
Log.d(TAG, "baseFile.exists() >>" + baseFile.exists()); // resulting TRUE
String path = "Android/data/package name/files/";
extPath = base + path;
Log.d(TAG, "exPath >>" + extPath);
File myFile = new File(Environment.DIRECTORY_DOWNLOADS + "/MY Download");
Log.d(TAG, "myFile >>" + myFile.getAbsolutePath());
File outputFile = new File(extPath, "" + myFile.getAbsolutePath());
if (!outputFile.exists()) {
Log.d(TAG, "Creating outputFile ....");
outputFile.mkdirs();
}
Log.d(TAG, "outputFile.exists() >>" + outputFile.exists() + "\n outputFile >>" + outputFile.getAbsolutePath());
} catch (Exception e) {
Log.d(TAG, "Exception >>" + Log.getStackTraceString(e));
}
Log.d(TAG, "end of crateDirectory() ");
}
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" />
I'm having problems with regards to creating a directory from an external storage, here is the method that I'm using.
public String createDir(String npath,String ndir,String file)
{
String[] paths = new String[] { npath, npath + ndir };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return "ERROR: Creation of directory " + path + " on sdcard failed";
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
if (!(new File(npath + ndir + file)).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(ndir + file);
OutputStream out = new FileOutputStream(npath + ndir + file);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copied " + file);
return "Copied " + file;
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + file + e.toString());
return "Unable to copy " + file + e.toString();
}
}
else
return "Error!";
}
But I always get "ERROR: Creation of directory " + path + " on sdcard failed". Not to mention this is already installed in an android device. I tried looking for the directory of my application, but it is nowhere to be found, that supposedly, should be creating its folder automatically after the installation of my APK. Anyone who can resolve this?
I have this code :
public void makeFile(String sFileName, int gene_ration)
{
try
{
//deleteFile("genetic_algorithm.txt");
if (!myfile.exists()) {
myfile.mkdirs();
}
File gpxfile = new File(myfile, sFileName);
FileWriter writer = new FileWriter(gpxfile, true);
writer.append("Generation " + gene_ration + "\r\n");
for(chromosomesNumber = 0; chromosomesNumber < indexOfChromosomes ; chromosomesNumber++)
{ writer.append(chromosomesNumber + ". " );
writer.append(population[chromosomesNumber] + " ");
writer.append("Nilai fitness : " + population[chromosomesNumber].fitness + "\r\n");
}
writer.append("\r\n");
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
String importError = e.getMessage();
}
}
I want to erase data on textfile every time I compile it and before add data to textfile. How can I do that? any idea?
There's a File.delete() method
http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#delete()