List of timestamps overrides the previous timestamp - java

I am using an arraylist to store list of timestamps of past 5 weeks.
i.e., if today is 2014-06-09, I want to store
2014-06-02
2014-05-26
2014-05-19
2014-05-12
2014-05-05
Here is my code.
public class Test {
public static void main(String ap[]) throws InterruptedException{
List<Timestamp> ts = new ArrayList<Timestamp>();
Timestamp t = new Timestamp(new java.util.Date().getTime());
Timestamp temp = null;
for(int i=0;i<5;i++){
t.setTime(t.getTime()-(7*24 * (long)60* (long)60) * (long)1000);
temp = t;
System.out.println(t);
ts.add(temp);
temp = null;
}
}
}
But the problem is always I am getting the list of overrided values i.e., list contains all the elements as last timestampI i.e 2014-05-05)
Can anybody reply to this question?

The reason you're not getting "new" timestamps is because you keep overriding the same one and adding it to the list - so you end up with the same object entered 5 times to the list and the last value will display in "all" the items. You don't need temp - simply create a new Timestamp object and add it to the list:
List<Timestamp> ts = new ArrayList<Timestamp>();
Timestamp t = new Timestamp(new java.util.Date().getTime());
for(int i=0;i<5;i++){
t.setTime(t.getTime()-(7*24 * (long)60* (long)60) * (long)1000);
System.out.println(t);
ts.add(new Timestamp(t.getTime()));
}

Related

How can I use a updated list in other if-else block?

I am a beginner and working with IntelijIDEA configurations first time.
Conditions of a task is:
When starting the program with the -c parameter, the program should add a person with the given parameters to the end of the allPeople list, and display the id (index) on the screen.
When starting the program with the -r parameter, the program should display data about a person with the given id according to the format specified in the task.
The current code:
public class Solution{
public static List<Person> allPeople = new ArrayList<Person>();
static
{
allPeople.add(Person.createMale("Иванов Иван", new Date())); //сегодня родился id=0
allPeople.add(Person.createMale("Петров Петр", new Date())); //сегодня родился id=1
}
public static void main(String[] args) throws ParseException
{
if (Objects.equals(args[0], "-c"))
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH);
Date date = sdf.parse(args[3]);
Person artman = Person.createMale(args[1], date);
allPeople.add(artman);
//trying to create a new list for updated allPeople list
//List<Person> allPeopleUpd = new ArrayList<Person>(allPeople);
}
if (Objects.equals(args[0], "-r"))
{
List<Person> allPeopleUpd = new ArrayList<Person>(allPeople); //it's not an updated list
String name = allPeopleUpd.get(Integer.parseInt(args[1])).getName();
String sex = String.valueOf(allPeopleUpd.get(Integer.parseInt(args[1])).getSex());
String bd = String.valueOf(allPeopleUpd.get(Integer.parseInt(args[1])).getBirthDate());
System.out.println(name + " " + sex + " " + bd);
}
}
}
How to do a first condition I understood, but the problem is that the second if statement (with a "-r" parameter) don't see a changes that I made in the first if statement. What should I do to make a updated list visible for the second if statement?
P.S. createMale() and getters are from another Person class, never mind

Why after split line into an array, the code after for-loop doesn't work?

In this cycle, the string within an arraylist is divided, and each word is inserted into an array. I only need the date that is in second position to compare it with a date that I pass. If it is not present, the entire string is deleted from the arraylist.
For this reason I use an iterator. Everything works but the code after the for loop doesn't work. Eliminating the insertion of words in the array works everything. I used the same method elsewhere and it works without problems, I don't understand.
CreateMap(ArrayList<String> eventi,String data) throws ParseException {
list_eventi = eventi;
intervallo = data;
String [] periodo;
String[] arrayData;
periodo = intervallo.split("-");
String data_in = periodo[0];
String data_fin = periodo[1];
SimpleDateFormat format = new SimpleDateFormat("ddMMyyyy");
Date dateIn = format.parse(data_in);
Date dateFin = format.parse(data_fin);
String[] line;
for (Iterator<String> iter = eventi.listIterator(); iter.hasNext(); ) {
String a = iter.next();
line = a.split(" "); //this is the problem//
String d = line[2];
Date dateImport = format.parse(d);
if(!dateImport.before(dateIn) && !dateImport.after(dateFin)) {
//date che sono nell'intervallo
// date between
System.out.println(d);
} else{
System.out.println("dati da eliminare " + a);
//iter.remove();
}
}
------------------------------ after this line the code doesn't execute
System.out.println("dati rimanenti");
System.out.println(list_eventi.toString());
//Map_for_login(eventi);
//Map_for_all(eventi);
There is no error message after executing the code, but after the for loop there are other methods and various system.out but they don't work
Since your variable eventi is an ArrayList you can just use the .forEach() method.
Fix:
List<String> resEventi = new ArrayList(); // the resulting eventi arrayList with only the correct values
eventi.forEach( a -> {
line = a.split(" ");
String d = line[2];
Date dateImport = format.parse(d);
if(!dateImport.before(dateIn) && !dateImport.after(dateFin)) {
//date che sono nell'intervallo
// date between
resEventi.add(a);
System.out.println(d);
} else{
System.out.println("dati da eliminare " + a);
}
});
This should work given you pass in proper data (there may be an exception raised by format.parse(d)).

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')

Check ArrayList contains any specific data

I have an Arraylist:
public static ArrayList<ScheduleItem>[] data = (ArrayList<ScheduleItem>[]) new ArrayList[30];
Also, I have an another ArrayList which contain 3 dates:
public static ArrayList<String> dateWay = new ArrayList<String>();
Now, I want to check if a certain day is in the data Arraylist. If not, only then it will parse json file. I tried with this but, It throws null pointer exception
if(!ScheduleItem.data[getPageNumber].get(pageNumber).getDate().equals(ScheduleItem.dateWay.get(pageNumber))){
//method to parse json
}
ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
Date date = new Date(); //set your date
for(ScheduleItem item: data){
if(date.equals(item.getDate()){
System.out.println("Contains the date");
}
}

Adding multiple values form database into RichList Blackberry

I am using Blackberry Plug-in and i am using Rich Lists of blackberry.
I want to make lists appear the same number of times as there are entries in the database table.
I m using the below code but it shows only one name in list view.
I need to show all the entries in database into list view...Kindly help me..
I have already used list.add(); inside the for loop but it is showing Exception: java.lang.IllegalStateException: Field added to a manager while it is already parented.
public static void richlistshow(){
String name = null;
list = new RichList(mainManager, true, 2, 0);
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
for (int c = 0; c < target_list.size();c++){
City tar_city = new City();
tar_city = (City)target_list.elementAt(c);
name = tar_city.get_city_name().toString();
}
//adding lists to the screen
list.add(new Object[] {delete,name,"time-date"});
}
You didn't posted full codes you are working with. But following code may help you to get rid of IllegalStateException. You were adding same BitmapField instance for every list entries, which caused the exception.
public static void richlistshow() {
final Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
list = new RichList(mainManager, true, 2, 0);
for (int c = 0; c < target_list.size(); c++) {
// create a new BitmapField for every entry.
// An UI Field can't have more than one parent.
final BitmapField delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
City tar_city = (City) target_list.elementAt(c);
final String name = tar_city.get_city_name().toString();
// add to list
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
list.add(new Object[] { delete, name, "time-date" });
}
});
}
}

Categories