combining the name of the file with todays date - java

I am creating an excel sheet in c: with this name ABC_0607 and it also get created as shown below..
String outputDir = "C:/Report/";
FileOutputStream fw = new FileOutputStream(new File(outputDir, "ABC_0607.xls"));
Now as I am recieving this files on a daily basis and need to be stored in c: drive
so I want to modify it name a little bit that is combination of filename+MM/DD/YYYY
so if today date is 3-July-2013 so file name should be like ABC_0607-MM/DD/YYYY that is ABC_0607-07/03/2013.
PLease advise how to achieve this

You can use this method to retrieve the name of your file:
public String getFileNameFrom(String name) {
String currDate = new SimpleDateFormat("yyyy_MM_dd").format(new Date());
return name + "-" + currDate;
}

Use a StringBuilder initialized with the name of the file.Format the Date using a DateFormat and append the String to it. Put the entire logic inside a method so that it can be reused without code duplication.

I have following code to create name for log file, it can be hourly, daily or minutely(lol)
SimpleDateFormat ymd = new SimpleDateFormat("yyyy_MM_dd");
SimpleDateFormat ymdh = new SimpleDateFormat("yyyy_MM_dd_HH");
SimpleDateFormat ymdhm = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
Calendar dt = Calendar.getInstance();
dt.setTimeInMillis(moment);
String fName;
if (_splitType == SPLIT_HOUR)
fName = ymdh.format(dt.getTime());
else if (_splitType == SPLIT_MINUTE)
fName = ymdhm.format(dt.getTime());
else
fName = ymd.format(dt.getTime());

Related

Java - Do not delete files that match any of the array values

I have a list of files(approximately 500 or more files) where the filename contains a date.
file_20180810
file_19950101
file_20180809
etc.
What I want to do is delete files which exceed the storage period.
I've come up with the following logic so far
~Get dates of valid storage period (ie. if storage period is 5 days and date today is 20180810, store date values 20180810, 20180809, 20180808, 20180807, 20180806, 20180805 in an array.
~Check every file in a directory if it contains any of the following dates. If it contains date, don't delete, else delete.
My problem here is, if the file name does contain one single date and I use a loop to delete a file, it might delete other files with valid dates as well. To show what I want to do in code form, it goes somehow like this:
if (!fileName.contains(stringDate1) &&
!fileName.contains(stringDate2) &&
!fileName.contains(stringDate3)) //...until storage period
{//delete file}
Is there a better way to express this? Any suggestions for a workaround?
Please and thank you.
Parse dates from your filename. Here's an example:
import java.time.*;
import java.util.regex.*;
public class MyClass {
public static void main(String args[]) {
LocalDate today = LocalDate.now();
long storagePeriod = 5L;
String fileName = "file_20180804";
int year = 0;
int month = 0;
int day = 0;
String pattern = "file_(\\d{4})(\\d{2})(\\d{2})";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(fileName);
if (m.find()) {
year = Integer.parseInt(m.group(1));
month = Integer.parseInt(m.group(2));
day = Integer.parseInt(m.group(3));
}
LocalDate fileDate = LocalDate.of(year, month, day);
if (fileDate.isBefore(today.minusDays(storagePeriod))) {
System.out.println("Delete this file");
}
}
}
You can try using Regex to extract the actual date of each file and check for the inclusion in a validity period.
Pattern p = Pattern.compile("file_(?<date>\d{6})");
foreach(File f : filelist){
Matcher m = p.matcher(f.filename());
if(m.find()){
Date fileDate = new Date(m.group("date"));
if(fileDate.before(periodStartDate)){
file.delete();
}
}
}
The code is not precise and should not compile, check about Date object creation and comparison, but the main idea is pretty much here.
You can only delete Files that are not in the Array like (tested, working):
String path = ""; // <- Folder we want to clean.
DateFormat df = new SimpleDateFormat("yyyyMMdd"); // <- DateFormat to convert the Calendar dates into our format.
Calendar cal = Calendar.getInstance(); // <- Using Calendar to get the days backwards.
ArrayList<String> dr = new ArrayList<String>(); // <- Save the dates we want to remove. dr = don't remove
dr.add(df.format(cal.getTime())); // <- add the actual date to List
for(int i = 0; i < 5; i++) { // <- Loop 5 Times to get the 5 Last Days
cal.add(Calendar.DATE, -1); // <- remove 1 day from actual Calendar date
dr.add(df.format(cal.getTime())); // <- add the day before to List
}
for(File file : new File(path).listFiles()) { // <- loop through all the files in the folder
String filename = file.getName().substring(0, file.getName().lastIndexOf(".")); // <- name of the file without extension
boolean remove = true; // <- Set removing to "yes"
for(String s : dr) { // <- loop through all the allowed dates
if(filename.contains(s)) { // <- when the file contains the allowed date
remove = false; // <- Set removing to "no"
break; // <- Break the loop for better performance
}
}
if(remove) { // <- If remove is "yes"
file.delete(); // <- Delete the file because it's too old for us!
}
}
but this is not the best way! A much better method would be to calculate how old the files are. Because of the _ you can pretty easily get the dates from the filenames. Like (not tested):
String path = ""; // <- Folder we want to clean.
Date today = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMdd"); // <- Dateformat you used in the files
long maxage = 5 * 24 * 60 * 60 * 1000; // <- Calculate how many milliseconds ago we want to delete
for(File file : new File(path).listFiles()) { // <- loop through all the files in the folder
String fds = file.getName().split("_")[1]; // <- Date from the filename as string
try {
Date date = df.parse(fds); // Convert the string to a date
if(date.getTime() - today.getTime() <= maxage) { // <- when the file is older as 5 days
file.delete(); // <- Delete the file
}
} catch (ParseException e) {
e.printStackTrace();
}
}
Here is some example code which demonstrates how a list of input files (file name strings, e.g., "file_20180810") can be verified against a supplied set of date strings (e.g., "20180810") and perform an operation (like delete the file) on them.
import java.util.*;
import java.io.*;
public class FilesTesting {
private static final int DATE_STRING_LENGTH = 8; // length of 20180809
public static void main(String [] args) {
List<String> filter = Arrays.asList("20180810", "20180808", "20180809", "20180807", "20180806", "20180805");
List<File> files = Arrays.asList(new File("file_20180810"), new File("file_19950101"), new File("file_20180809"));
for (File file : files) {
String fileDateStr = getDateStringFromFileName(file.getName());
if (filter.contains(fileDateStr)) {
// Do something with it
// Delete file - if it exists
System.out.println(file.toString());
}
}
}
private static String getDateStringFromFileName(String fileName) {
int fileLen = fileName.length();
int dateStrPos = fileLen - DATE_STRING_LENGTH;
return fileName.substring(dateStrPos);
}
}
If you’re using ES6 you can use array includes and return a true or false to validate.
['a', 'b', 'c'].includes('b')

selecting files with regex

I'm doing a project at college where my method is using a regex to pull the date out of the name of each of the log files in a folder, and then, after comparing the millisec stamp with one defined by the Ndays parameter passed in, delete it if its older than the required date (eg; 30 days ago- params passed in will be 30 and the file that contains the logs)....
Much appreciate any assistance.....my below attempt isn't working.....
public void deleteFilesOlderThanNdays( int Ndays, String aFolder) throws
ParseException{
File directory = new File(aFolder);
if(directory.exists()){
File[] logFiles = directory.listFiles();
for (File log: logFiles) {
String name= log.getName();
//Pattern dateFind = Pattern.compile("\\d\\{0,10}");// or
Pattern dateFind = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
Matcher dateSearch =dateFind.matcher(name);
while(dateSearch.find()){
String logDate = dateSearch.toString();
SimpleDateFormat format= new SimpleDateFormat("yyyy.mm.dd");
Date date= format.parse(logDate);
long cutOffPoint = System.currentTimeMillis() - (Ndays* 24*60*60*1000);
if(date.getTime()< cutOffPoint){
log.delete();
}
}
}
}
}
It turned out to be the simple mistakes pointed out by the replies above, the mm in the date format instead of the MM, and calling the group() method in place of toString() method on the Matcher object..regards guys....

Command manager procedure in MicroStrategy not converting to date

I am running below command manager procedure in Microstrategy but it does not convert the string into date, tried lot of options. Can someone please assist?
*********** PROCEDURE***************************************
String sQuery = "LIST ALL SUBSCRIPTIONS FOR SCHEDULE \"" + sScheduleName + "\" FOR PROJECT \"" + projectName + "\";";
ResultSet oSubs=executeCapture(sQuery);
oSubs.moveFirst();
while(!oSubs.isEof()){
String sSubsName = oSubs.getFieldValueString(DisplayPropertyEnum.GUID);
ResultSet RecList = executeCapture("LIST ALL PROPERTIES FOR SUBSCRIPTION GUID " +sSubsName+ " FOR PROJECT \"projectname\";");
RecList.moveFirst();
while(!RecList.isEof()){
ResultSet oResultSetSubProps = (ResultSet)RecList.getResultCell(SUBSCRIPTION_RESULT_SET).getValue();
oResultSetSubProps.moveFirst();
while(!oResultSetSubProps.isEof())
{
String d1 = oResultSetSubProps.getFieldValueString(DisplayPropertyEnum.EXPIRATIONDATE);
// the below few lines in red return nothing, its unable to convert to Date as it is unable to recognize the Expiration date in the String format.
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("M/dd/yyyy");
String dateInString = d1;
Date date = formatter.parse(dateInString);
printOut(formatter.format(date));
oResultSetSubProps.moveNext();
}
RecList.moveNext();
}
oSubs.moveNext();
}
This worked for me. The string was neither empty, nor null and no even blank but it would still not parse it so i had to use the length of the string.
java.text.DateFormat formatter = new java.text.SimpleDateFormat("M/d/yyyy",Locale.US);
String dateInString = d1;
if(d1.trim().length()>0)
{
Date date = formatter.parse(dateInString);
if(todaydate.compareTo(date)>0)
{
printOut(name+";"+formatter.format(date));
}
}
if(d1.contains("/"))
{
Date EDate=new Date(d1);
Date today= new Date();
if(d1.compareTo(today)<0)
{
printOut("Expired");
}
}
else
{
printOut("Active");
}
//blank or null values can be handled in Else condition instead.. Hope it helps..

Converting datepicker to string

How do you convert a DatePicker value to a String?
Currently I have a TextView setup, which the DatePicker passes its value to. Its displayed fine. Using that String to pass to a SQLite database isn't working however and returns
android.widget.TextView#41258880
When the databases fields are pulled up. I am currently taking the value and passing it to a string within the following TRY/Catch statement:
case R.id.btnUpdateDB:
boolean worked = true;
try {
String dbWeight = curWeight.getText().toString();
String dbWaist = curWaist.getText().toString();
String dbChest = curChest.getText().toString();
String dbLegs = curLegs.getText().toString();
String dbArms = curArms.getText().toString();
String dbDate = displayDate.toString();
Stats entry = new Stats(MainActivity.this);
entry.open();
entry.createEntry(dbWeight, dbWaist, dbChest, dbLegs, dbArms, dbDate);
entry.close();
break;
I feel that the following line is incorrect:
String dbDate = displayDate.toString();
You called the method toString directly on the widget. According to the source code it prints :
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
That's why you get :
android.widget.TextView#41258880
You have to do instead :
String dbDate = displayDate.getText().toString();
if displayDate is TextView You get its value just like You do with other fields before
String dbDate = displayDate.getText().toString();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
String dateFormat = dateformat.format(new Date(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth()));

Format date in String Template email

I'm creating an email using String Template but when I print out a date, it prints out the full date (eg. Wed Apr 28 10:51:37 BST 2010). I'd like to print it out in the format dd/mm/yyyy but don't know how to format this in the .st file.
I can't modify the date individually (using java's simpleDateFormatter) because I iterate over a collection of objects with dates.
Is there a way to format the date in the .st email template?
Use additional renderers like this:
internal class AdvancedDateTimeRenderer : IAttributeRenderer
{
public string ToString(object o)
{
return ToString(o, null);
}
public string ToString(object o, string formatName)
{
if (o == null)
return null;
if (string.IsNullOrEmpty(formatName))
return o.ToString();
DateTime dt = Convert.ToDateTime(o);
return string.Format("{0:" + formatName + "}", dt);
}
}
and then add this to your StringTemplate such as:
var stg = new StringTemplateGroup("Templates", path);
stg.RegisterAttributeRenderer(typeof(DateTime), new AdvancedDateTimeRenderer());
then in st file:
$YourDateVariable; format="dd/mm/yyyy"$
it should work
Here is a basic Java example, see StringTemplate documentation on Object Rendering for more information.
StringTemplate st = new StringTemplate("now = $now$");
st.setAttribute("now", new Date());
st.registerRenderer(Date.class, new AttributeRenderer(){
public String toString(Object date) {
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy");
return f.format((Date) date);
}
});
st.toString();
StringTemplate 4 includes a DateRenderer class.
My example below is a modified version of the NumberRenderer on the documentation on Renderers in Java
String template =
"foo(right_now) ::= << <right_now; format=\"full\"> >>\n";
STGroup g = new STGroupString(template);
g.registerRenderer(Date.class, new DateRenderer());
ST st = group.getInstanceOf("foo");
st.add("right_now", new Date());
String result = st.render();
The provided options for format map as such:
"short" => DateFormat.SHORT (default)
"medium" => DateFormat.MEDIUM
"long" => DateFormat.LONG
"full" => DateFormat.FULL
Or, you can use a custom format like so:
foo(right_now) ::= << <right_now; format="MM/dd/yyyy"> >>
You can see these options and other details on the DateRenderer Java source here
one very important fact while setting date format is to use "MM" instead of "mm" for month. "mm" is meant to be used for minutes. Using "mm" instead of "MM" very generally introduces bugs difficult to find.

Categories