Renaming file if exists in Android - android

I have been looking at the forum and found some tips but none of them bring me to the final solution. I need the code if possible, please.
I am creating a txt file every time I close my app and what I am aiming for is to rename the file in case it already exists with the following format:
file.txt - file(1).txt - file(2).txt
Up until now what I get is the following:
file.txt - file.txt1 - file.txt12
The code that I have is the following:
int num = 0;
public void createFile(String name) {
try {
String filename = name;
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++;
createFile(filename + (num));
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks everybody in advance!

Your filename variable contains the whole name of your file (i.e. file.txt). So when you do this:
createFile(filename + (num));
It simply adds the number at the end of the file name.
You should do something like this:
int num = 0;
public void createFile(String prefix) {
try {
String filename = prefix + "(" + num + ").txt"; //create the correct filename
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++; //increase the file index
createFile(prefix); //simply call this method again with the same prefix
}
} catch (IOException e) {
e.printStackTrace();
}
}
Then just call it like this:
createFile("file");

Related

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" />

MediaScannerConnection doesn't work

public void onClick(View v) {
// Writing data to file
FileWriter fw;
try {
fw = new FileWriter(Environment.getExternalStorageDirectory()+"/DataLog.csv", true);
BufferedWriter br = new BufferedWriter(fw);
br.append(formattedDate + String.valueOf(location.getLatitude()) +
";" + String.valueOf(location.getLongitude()) +
";" + String.valueOf(location.getSpeed()) +
";" + String.valueOf(location.getBearing()) +
";" + String.valueOf(location.getAltitude()) +
";" + String.valueOf(location.getAccuracy()));
br.append("\r\n");
br.close();
fw.close();
// MediaScanner scans the file
MediaScannerConnection.scanFile(MainActivity.this, new String[] {fw.toString()} , null, new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Toast t = Toast.makeText(MainActivity.this, "Scan comlete", Toast.LENGTH_LONG);
t.show();
}
} );
} catch (IOException e) {
e.printStackTrace();
}
}
I tried a code to write data to a DataLog.csv file in the sd root. The code creates the file with the data but i cannot see the file in windows when browsing the sdcard.
I saw this video and followed the instructions but it is not working for me. Maybe the fw variable is not good to define the file?
File csv = new File (Environment.getExternalStorageDirectory(), "DataLog.csv");
MediaScannerConnection.scanFile(
MainActivity.this,
new String[] {csv.getAbsolutePath()},
null, null);
I tried your advice like this but it still doing nothing.
toString() on FileWriter does not return the path to the file, which you are assuming it does, in the second parameter you pass to scanFile().

how to delete all check file using for loop?

This is my code which deletes only the first checked file.
I want to delete all checked files, what changed do I need to make?
How do I collect all values in CheckArr[i]?
The code only deletes the first checked file in grid. I want to first collect all checked values which are true then make database call(s).
boolean CheckArr[];
File[] currentFiles;
unhide.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < CheckArr.length; i++) {
if (CheckArr[i] == true) {
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
Cursor DataC = db
.selectQuery("SELECT path FROM Photos where name ='" +
currentFiles[i].getName() + "'");
if (DataC.getCount() > 0) {
Bitmap bitmap =
decodeFile.decodeFile(new File(root + "/" + currentFiles[i].getName()));
try {
FileOutputStream
outputStream = new FileOutputStream(
new File(DataC.getString(DataC
.getColumnIndex("path"))));
outputStream.write(decodeFile.getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(root + "/" +
currentFiles[i].getName());
file.delete();
inflateListView(currentFiles);
}
DataC.close();
db.close();
}
}
You have to add a loop for the cursor DataC to delete all the files and not just the first one.
if (DataC.getCount() > 0) {
while (DataC.moveToNext()) {
//...
}
}

Is it possible to create and maintain a folder structure with files Using the Internal Storage

I have studied the link below, but it doesn't answer my question.
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
If the answer to the question in the title is yes. Could someone
please supply a simple example creating a subfolder and adding a file
to that folder? And perhaps show how to read the file back from the
sub folder?
Or maybe tell me why the example below fails miserably
Works now after changing file.mkdirs(); to file.getParentFile().mkdirs();
Se explanation in the following Answer
public static void Test(String path, String fileName, String fileStr, Context ctx)
{
SaveFile(path, fileName, fileStr, ctx);
String returnFileStr = ReadFile(path, fileName, ctx);
}
public static Boolean pathExists(String path, Context ctx)
{
Boolean result = false;
String[] pathSeqments = path.split("/");
String pathStr = "";
for(int i = 0;i<pathSeqments.length;i++ )
{
pathStr += pathSeqments[i];
if(!new File(ctx.getFilesDir() +"/" + pathStr).exists())
{
result = false;
break;
}
pathStr += "/";
result = true;
}
return result;
}
public static void SaveFile(String path, String fileName, String fileStr, Context ctx) {
try {
File file = new File(ctx.getFilesDir() +"/" + path, fileName); //new File(ctx.getFilesDir() +"/" + path + "/" + fileName);
file.getParentFile().mkdirs();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(fileStr);
osw.flush();
osw.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public static String ReadFile(String path, String fileName, Context ctx) {
String fileStr = null;
try {
if(pathExists(path, ctx))
{
File file = new File(ctx.getFilesDir() +"/" + path, fileName);
FileInputStream fIn = new FileInputStream(file);
StringWriter writer = new StringWriter();
IOUtils.copy(fIn, writer, "UTF-8");
fileStr = writer.toString();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return fileStr;
}
Is it possible to create and maintain a folder structure with files Using the Internal Storage
Yes, using standard Java I/O.
Or maybe tell me why the example below fails miserably
Talented programmers know how to describe symptoms, rather than use pointless phrases like "fails miserably".
That being said, file.mkdirs(); creates a directory. You then try opening that directory as if it were a file, for the purposes of writing data to it. That does not work on any OS that I am aware of, and certainly not on Android. Please call mkdirs() on something that will create the file's parent directory (e.g., file.getParentFile().mkdirs()).
Also, never use concatenation to create a File object. Use the proper File constructor.

Running my own camera

I'm a beginner to Java and Android, and I have a problem with launching a camera. Precisely I need a small camera preview that would be under my control. (I want to put a sight in the middle of it). I tried to paste this to my project:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/CameraPreview.html
But there are loads of errors, after my naive 'fixing', program crashes, before starting anything..
I tried searching google for quite a long time, unsuccessfully.
Is somebody in posession of something that would just work without problems? A project would be nice :)
Thanks in advance
Bye
in your onCreate method, provide the below lines,
String imgName = getImageName();
startCamera(imgName);
And below your onCreate, provide these methods. your camera is ready.
private void startCamera(String ImageName) {
Intent cameraIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
Uri.fromFile(new File(ImageName)));
startActivityForResult(cameraIntent, TAKE_PICTURE_WITH_CAMERA);
}
private String getImageName() {
String imgname = "";
String imgpath = "";
String strDirectory="/sdcard";
try {
imgname = String.format("%d.mp4", System.currentTimeMillis());
imgpath = strDirectoy + "/" + imgname;
File file = new File(strDirectoy);
boolean exists = file.exists();
if (!exists) {
boolean success = (new File(strDirectoy)).mkdir();
if (success)
Log.e("Directory Creation", "Directory: " + strDirectoy
+ " created");
else
Log.e("Directory Creation", "Error in Create Directory");
}
Log.i("Imagename : ", imgpath);
} catch (Exception e) {
Log.e("fileException", e.getMessage());
e.printStackTrace();
}
return imgpath;
}

Categories

Resources