How to get autogenerated folder path in java to parse files from folder
On Unix a folder path is created, eg /data/test/files/2015/05/19
. Starting from the year, the folder is autogenerated/data/test/files/$(date +%Y)/$(date +%m)/$(date +%d)
So the .txt
file inside the specified folder has to be parsed with Java code and moved to DB.
I tried to parse this location as it 2015/05/19
will change in the future, so I tried to add the current year / month / day in Java and then parse that particular file.
//To get current year
String thisYear = new SimpleDateFormat("yyyy").format(new Date());
System.out.println("thisYear :"+thisYear);
//To get current month
String thisMonth = new SimpleDateFormat("MM").format(new Date());
System.out.println("thisMonth : "+thisMonth);
//To get current date
String thisDay = new SimpleDateFormat("dd").format(new Date());
System.out.println("thisDay : "+thisDay);
File f = new File("\\data\\test\\files\\+"thisYear"+\\+"thisMonth"+\\+"thisDay"+ \\refile.txt");
The above doesn't work, so how can I use thisYear,thisMonth,thisDay
in path?
source to share
You can use the SimpleDateFormat class like:
String format = "yyyy/MM/dd".replace( "/" , File.separator );
SimpleDateFormat sdf = new SimpleDateFormat( format );
String pathPrefix = "/data/test/files/".replace( "/" , File.separator );
File f = new File( pathPrefix + sdf.format( new Date() ) + File.separator + "refile.txt" );
Remember that the path separator character is filesystem dependent and is therefore used File.separator
. You can also replace new Date()
with something else if you are not following the "today" directory.
If you need to scan all directories with a date, that's a different matter for a different question, but look at the methods File.list()
for that.
Greetings,
source to share