Get the newest file based on timestamp in Java - java

I have a directory which contains files in the following format. The files are in a diretory called /incoming/external/data
ABC_20100806.csv
ABC_20100807.csv
ABC_20100808.csv
ABC_20100809.csv
ABC_20100810.csv
ABC_20100811.csv
ABC_20100812.csv
As you can see the filename of the file includes a timestamp. i.e. [RANGE]_[YYYYMMDD].csv
What i need to do is find out which of these files has the newest date using the timestamp on the filename not the system timestamp and store the filename in a variable and move it to another directory and move the rest to a different directory in java.

You can read the filenames into an array using:
File directory = new File("/incoming/external/data");
String[] fileNames = directory.list(new FilenameFilter() {
public boolean accept(File dir, String fileName) {
return fileName.endsWith(".csv");
}
});
And from there simply sort the array if your files always have the same prefix:
Arrays.sort(fileNames);
One way you can remove the prefix and suffix of each fileName to extract the date is:
int underline = fileName.indexOf("_");
int dot = fileName.indexOf(".");
String datePart = fileName.substring(underline, dot);
And then you can add that string to an array and sort (lexically).
If for some other reason you want to convert the dates into Java Dates, you can use:
SimpleDateFormat dt = new SimpleDateFormat("yyyymmdd");
Date date = dt.parse(datepart);
And you'll have a Java date, which you can also sort in an array or list.

Related

How to construct a file from a relative path in a File

I'm parsing a base file at this location:
/Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml
And from that file, I parse out:
../../../../include/masking.xml
So that relative path is from the context from the file I parsed it out from (base file)
How can I constuct a file object from that relative path so I can read it's contents?
Since you tagged nio, the Path class makes this easy. You simply call resolveSibling() and normalize().
String main = "/Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml";
String ref = "../../../../include/masking.xml";
System.out.println(Paths.get(main));
System.out.println(Paths.get(main).resolveSibling(ref));
System.out.println(Paths.get(main).resolveSibling(ref).normalize());
Or:
System.out.println(Paths.get(main));
System.out.println(Paths.get(main, ref));
System.out.println(Paths.get(main, ref).normalize());
Output
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\print.xml
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\..\..\..\..\include\masking.xml
\Users\haddad\development\fspc\content\2017.dev\src\agency\include\masking.xml
Note: I ran this on a Window machine, so I of course got backslashes
If you prefer the old File object, you use the two-argument constructor, and call getCanonicalFile().
System.out.println(new File(main));
System.out.println(new File(main, ref));
System.out.println(new File(main, ref).getCanonicalFile());
Output
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\print.xml
\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\integration\src\forms\print.xml\..\..\..\..\include\masking.xml
C:\Users\haddad\development\fspc\content\2017.dev\src\agency\individual\include\masking.xml
You could use subpath() to keep the path part that interests you that you can combine with resolve() to append a new path to :
public static void main(String[] args) {
Path printXmlPath = Paths.get("/Users/haddad/development/fspc/content/2017.dev/src/agency/individual/integration/src/forms/print.xml");
Path maskingXmlPath = printXmlPath.subpath(0, printXmlPath.getNameCount() - 5)
.resolve("include/masking.xml");
System.out.println(maskingXmlPath);
}
Users\haddad\development\fspc\content\2017.dev\src\agency\include\masking.xml

Need help in WildcardFileFilter in java

I have to separate out those files from a folder which matches one of the given pattern. I have an array of strings which contains these patterns. And I am passing this array as argument into WildCardFilter so that I can separate out thse files which matches the given pattern in the array. My code is given below.
String pat1="DailyExistingBusinessReport_*";
String pat2="*DailyNewExistingBusinessReport_.csv";
String pat3="*_EOD_PNL_Explained.*";
String pat4="ABC*XYZ.csv";
String str[]=new String[]{pat1,pat2,pat3,pat4};
FileFilter fileFilter = new WildcardFileFilter(str);
File dir = new File("\\C:\\Users\\ABC\\Desktop\\Myfiles");
File[] files = dir.listFiles(fileFilter);
for(File f :files){
System.out.println(f);
}
This prints out the name of files which matches the patterns given in array. But now my requirement is that alongwith each file name, I want the exact name of pattern to which this file matched. Any idea what code should I add further to get pattern name alongwith file name.
I've checked the API and don't see the way to do that with the FileFilter.
I suggest creating a list of filters and apply them one by one:
List<FileFilter> filters = new ArrayList<FileFilter>();
filters.add(new WildCardFileFilter("DailyExistingBusinessReport_*");
filters.add(new WildCardFileFilter("*DailyNewExistingBusinessReport_.csv");
filters.add(new WildCardFileFilter("*_EOD_PNL_Explained.*");
filters.add(new WildCardFileFilter("ABC*XYZ.csv");
File dir = new File("\\C:\\Users\\ABC\\Desktop\\Myfiles");
Map<FileFilter, List<File>> filemap = new HashMap<FileFilter, List<File>>();
for (File file: dir.listFiles()){
for(FileFilter filter: filters){
if(filter.accept(file)){
if(!filemap.containsKey(filter)){
filemap.put(filter, new ArrayList<File>());
}
filemap.get(filter).add(file);
}
}
}
After that, you should have a map which contain filters and lists of files for which the filter apply.
I don't have IDE by hand, so there may be some small mistakes.

display files from a directory with their time stamps [last modified date] so that to move least used files to a temporary folder [duplicate]

This question already has answers here:
Finding the 3 most recently modified files in a long list of files
(4 answers)
Closed 9 years ago.
import java.io.*;
import java.util.*;
import java.text.*;
public class test
{
public static void main(String[] args)
{
String path = "C:/stuff/";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println(listOfFiles[i].getName());
}
}
}
this is my code. i want to display timestamps [last modified] details along with the file name in a sorted manner. please help..
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println(listOfFiles[i].getName()+"\t"+new Date(listOfFiles[i].lastModified()));
}
About display timestamp you can do as follows:
System.out.println(String.format("%s-%s", listOfFiles[i].getName(),
listOfFiles[i].lastModified()));
listOfFiles[i].lastModified() return the timestamp. If you need change it to Date, you can reference the link as follows:
Pick day, month and year out file.lastModified();.
About display the filename in sorted manner, you can reference the link as follows:
Best way to list files in Java, sorted by Date Modified?
File Class provide function to get last modify date for that file.
You may use below code to get last modify date :
File file = new File("Your_File_Name");
System.out.println("Before Format : " + file.lastModified());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("After Format : " + sdf.format(file.lastModified()));
Here is JAVA Doc Reference.
For sorting file list based on File Name you may refer This Question.

Insert a string in the middle of text file without replacing [duplicate]

This question already has answers here:
inserting data in the middle of a text file through java
(2 answers)
Closed 9 years ago.
Suppose i have a text file named Sample.text.
i need advice on how to achieve this:
Sample.txt before running a program:
ABCD
while running the program, user will input string to be added starting at the middle
for example: user input is XXX
Sample.txt after running a program:
ABXXXCD
Basically you've got to rewrite the file, at least from the middle. This isn't a matter of Java - it's a matter of what file systems support.
Typically the way to do this is to open both the input file and an output file, then:
Copy the first part from the input file to the output file
Write the middle section to the output file
Copy the remainder of the input file to the output file
Optionally perform file renaming if you want the new file to have the same eventual name as the original file
The basic idea is to read the file contents into memory, say at program start, manipulate the string as desired, then write the entire thing back to the file.
So you would open and read in Sample.txt. In memory you have a string = "ABCD"
in your program execution, accept user input of XXX. Insert that into your string with your favorite string manipulation method. Now string = "ABXXXCD"
Finally you would overwrite Sample.txt with your updated string and close it.
If you were worried about corruption or something, you might save it to a secondary file, then verify its contents, delete the original, and rename the new to be the same as the original.
Actually i have did something like what you want, here try this code, its not a complete but it should give you a clear idea:
public void addString(String fileContent, String insertData) throws IOException {
String firstPart = getFirstPart(fileContent);
Pattern p = Pattern.compile(firstPart);
Matcher matcher = p.matcher(fileContent);
int end = 0;
boolean matched = matcher.find();
if (matched) {
end = matcher.end();
}
if(matched) {
String secondPart = fileContent.substring(end);
StringBuilder newFileContent = new StringBuilder();
newFileContent.append(firstPart);
newFileContent.append(insertData);
newFileContent.append(secondPart);
writeNewFileContent(newFileContent.toString());
}
}
Normally a new file would be created, but the following probably suffices (for non-gigabyte files). Mind the explicit encoding UTF-8; which you can ommit for the encoding of the operating system.
public static void insertInMidstOfFile(File file, String textToInsert)
throws IOException {
if (!file.exists()) {
throw new FileNotFoundException("File not found: " + file.getPath());
// Because file open mode "rw" would create it.
}
if (textToInsert.isEmpty()) {
return;
}
long fileLength = file.length();
long startPosition = fileLength / 2;
long remainingLength = fileLength - startPosition;
if (remainingLength > Integer.MAX_VALUE) {
throw new IllegalStateException("File too large");
}
byte[] bytesToInsert = textToInsert.getBytes(StandardCharsets.UTF_8);
try (RandomAccessFile fh = new RandomAccessFile(file, "rw")) {
fh.seek(startPosition);
byte[] remainder = new byte[(int)remainingLength];
fh.readFully(remainder);
fh.seek(startPosition);
fh.write(bytesToInsert);
fh.write(remainder);
}
}
Java 7 or higher.

Truncate a String from a file name

I have previously written a code where I have added a time stamp to a file once it has been save in a directory.
Now I wanna to be able to truncate the time stamp from the file which comes after the extension .txt
note that my time stamp format is:_yyyy-mm-dd.
If you have the date after your extension in the form _yyyy-mm-dd just can use
String strippedFileName = fileName.substring(0, fileName.length() - 11);
or a bit nicer
String dateFormatString = "_yyyy-mm-dd";
String strippedFileName = fileName.substring(0, fileName.length() - dateFormatString.length());
You could also do this:
String trimmed = filename.replaceAll(".{11}$", "");

Categories