Within my application I am saving data from a game to a .txt file.
I am having the problem at the minute that the String name of the text file is causing the file to be split into two if the game is played over more than a minute.
E.g. if its played over 9.22am and 9.23am then two sperate files are created.
How can I create a more suitable file name, that will be unique for each file.
Code relating to name of text file:
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
Full write to file method:
public void writeToFileEEGPower(String data){
Time t= new Time();
t.setToNow();
int timeFileMinute= t.minute;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "Maths-" +timeFileMinute + timeFileDate + timeFileYear + android.os.Build.SERIAL;
//creating the file where the contents will be written to
File file= new File(dir, fileName + ".txt");
FileOutputStream os;
try{
boolean append= true;
os= new FileOutputStream(file, append);
String writeMe =data + "\n";
os.write(writeMe.getBytes());
os.close();
} catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
EDIT: You should first consider other strategies for generating unique files names like random ones.
You can do it this way:
String fileName = new Date().getTime() + '.txt';
or
String fileName = new SimpleDateFormat("YYYYMMDDhhmmss'.txt'").format(new Date().getTime());
A way to generate file names randomly is:
String name = String.format("%s.txt", RandomStringUtils.randomAlphanumeric(10));
Have a look at this related SO questions:
Current Timestamp as File name in Java
What is the best way to generate a unique and short file name in Java
Related
How can I save a file to external storage with a predefined name for example like myfile_date.mp4?
For external storage we do something like this with basic intelligence..:
private String getFilename()
{
String timeStamp = new SimpleDateFormat("ddMMYYYY").format(new Date());
String MySound = "MySound";
String DefinedName = MySound+timeStamp;
filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + DefinedName + file_exts[currentFormat]);
}
I'm developing an app in which I'm sending a .txt file from one end by attaching it with gmail. Everytime this file is sent, its name is data.txt. When this file is downloaded at the other end, on the first download its name is the same, i.e. data.txt. However, when another file is sent with the same name, the name of the file at the receiveing end becomes data-1.txt, data-2.txt etc. And because of this, I'm not able to read the proper file. Please could someone give me some suggestions to solve this problem? The sending and receiving code is given below: SEND
bSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
String toWrite = enterText.getText().toString();
FileOutputStream fos;
try {
String path = Environment.getExternalStorageDirectory().toString();
Log.v("path", path);
File myFile = new File("" + path + "/" + fileName + ".txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(toWrite);
Log.v("file written", toWrite);
myOutWriter.close();
fOut.close();
Uri u1 = null;
u1 = Uri.fromFile(myFile);
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "MPPT Configuration Data");
sendIntent.putExtra(Intent.EXTRA_STREAM, u1);
sendIntent.setType("text/html");
startActivity(sendIntent);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
READ:
bRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fileName = "data";
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/storage/sdcard0/download/" + fileName + ".txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
Log.v("read data", "" + aBuffer);
tvData.setText(aBuffer);
}catch (IOException e2) {
e2.printStackTrace();
}
}
});
I found a possible solution. I can link the file manager (external app) from where the user can pick out whichever file he wants to be read.
Thanks #greenapps fir the idea of displaying a list of files.
You can get all the file by using regex ,then process the file by following way:
1.if only one file found,read it;
2.if more than one file found, compare and read the file which last number is biggest
but this solution still has one problem,if has file data.txt and data-3.txt ,the file we want to read may become data-2.txt,but what we really read is data-3.txt.
Or,maybe you can get the file you want by judging file established time.
I created a csv file with the following format which I'm aiming to output to the device's sd card:
Ship Name,Scientist Name,Scientist Email,Sample Volume,Sample Colour,Longitude,Latitude,Material,Date
Each of the vales in the csv will be of type string except for the last value of date.
The name of the csv file is AnalysisData.csv
I've looked examples on Stackoverflow such as this, Export my data on CSV file from app android but this creates a new file which I don't want.
I have already added the opencsv jar to my project so just need a relevant example.
Does anyone have any advice on achieving this in Android?
Try with this code snippet :
String baseDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "AnalysisData.csv";
String filePath = baseDir + File.separator + fileName;
File f = new File(filePath);
CSVWriter writer;
// File exist
if(f.exists()&&!f.isDirectory())
{
mFileWriter = new FileWriter(filePath, true);
writer = new CSVWriter(mFileWriter);
}
else
{
writer = new CSVWriter(new FileWriter(filePath));
}
String[] data = {"Ship Name", "Scientist Name", "...", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").formatter.format(date)});
writer.writeNext(data);
writer.close();
I've wrote method below to copy my backup file to external storage
public Boolean Backup() {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
File sd = Environment.getExternalStoragePublicDirectory("");
File data = Environment.getDataDirectory();
String dbPath = "//data//" + "com.example.sqlitetest"
+ "//databases//" + "TestDB";
// Backup file name
Calendar calendar = Calendar.getInstance();
String backupName = calendar.get(Calendar.YEAR) + "-"
+ (calendar.get(Calendar.MONTH) + 1) + "-"
+ calendar.get(Calendar.DAY_OF_MONTH) + "-"
+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
+ calendar.get(Calendar.MINUTE) + ":"
+ calendar.get(Calendar.SECOND);
String backupPath = "//BackupFiles";
File db = new File(data, dbPath);
File backup = new File(sd + backupPath, backupName);
if (!backup.exists())
backup.mkdirs();
FileChannel src = new FileInputStream(db).getChannel();
FileChannel dest = new FileOutputStream(backup).getChannel();
dest.transferFrom(src, 0, src.size());
src.close();
dest.close();
return true;
} else
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
I've added permissions to write and read external storage. The destination folder is created (sd + backupPath) but files no and throws FileNotFoundException! How can I solve this problem?
Thanks in advance
Try:
String dbPath = context.getApplicationInfo().dataDir + File.separator
+ "databases" + File.separator + "TestDB";
And instead of using //, try File.separator.
Your dbPath variable is already a full absolute path name, so can't be used in combination with a File object referring to your data directory, but only on its own. And you got that full path name by making poor assumptions anyway.
What you should do is obtain a File representing the data directory as you are, and use it in combination with a String containing just a filename (within that) and not an absolute directory path.
If you do decide you want directories under your data directory, you can do that, but will have to make sure they exist or create them.
I want to replace a character in a file and copy the contents to a temp file and rename the temp file to original file.
path = "/mnt/sdcard/TESTfile/"
File _f = new File(path);
File[] _f1 = _f.listFiles();
String[] s1 = { "t1.txt", "t2.txt", "t3.txt" };
_fOut = new FileOutputStream(path + File.separator + s1[i]);
// Copy the bits from input stream to output stream
StringBuffer sb = null;
BufferedWriter out = null;
while ((line = reader.readLine()) != null) {
line = line.replaceAll("a"," ").replaceAll("g"," ");
sb = new StringBuffer();
Log.i("Line>>>" + line, "<<<<<");
sb.append(line);
s = sb.toString();
byte[] temp = s.getBytes();
_fOut.write(temp);
}
fis.close();
_fOut.close();
//old file name with path
String path1 = path + File.separator + s1[i];
//new file name with path
String rename1 = path + File.separator + _f1[i].getName();
File oldFile = new File(path1);
File renameFile = new File(rename1);
for(int j = 0; j < _f1.length;j++)
{
oldFile.renameTo(renameFile);
}
This is how i tried to do it. I am not sure how to rename the file and delete the original file. Please help
To rename a file, you need 2 File objects. Create one using the original path and the second using the new name. Then call original.renameTo(newFile).
Deleting a file is even easier. Android contexts have a method called deleteFile(name). Call it to delete a file. Keep in mind that that method deletes a file from the local storage folders only and doesn't accept path separators. If you want to delete a file from a different location, there is a file.delete() method you could use too.