Java - get the newest file in a directory? - java

Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?

The following code returns the last modified file or folder:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required Java 8 or newer due to the lambda expression.

In Java 8:
Path dir = Paths.get("./path/somewhere"); // specify your directory
Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
.filter(f -> !Files.isDirectory(f)) // exclude subdirectories from listing
.max(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field
if ( lastFilePath.isPresent() ) // your folder may be empty
{
// do your code here, lastFilePath contains all you need
}

This works perfectly fine for me:
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
...
/* Get the newest file for a specific extension */
public File getTheNewestFile(String filePath, String ext) {
File theNewestFile = null;
File dir = new File(filePath);
FileFilter fileFilter = new WildcardFileFilter("*." + ext);
File[] files = dir.listFiles(fileFilter);
if (files.length > 0) {
/** The newest file comes first **/
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
theNewestFile = files[0];
}
return theNewestFile;
}

private File getLatestFilefromDir(String dirPath){
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}

Something like:
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
public class Newest {
public static void main(String[] args) {
File dir = new File("C:\\your\\dir");
File [] files = dir.listFiles();
Arrays.sort(files, new Comparator(){
public int compare(Object o1, Object o2) {
return compare( (File)o1, (File)o2);
}
private int compare( File f1, File f2){
long result = f2.lastModified() - f1.lastModified();
if( result > 0 ){
return 1;
} else if( result < 0 ){
return -1;
} else {
return 0;
}
}
});
System.out.println( Arrays.asList(files ));
}
}

public File getLastDownloadedFile() {
File choice = null;
try {
File fl = new File("C:/Users/" + System.getProperty("user.name")
+ "/Downloads/");
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
//Sleep to download file if not required can be removed
Thread.sleep(30000);
long lastMod = Long.MIN_VALUE;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
} catch (Exception e) {
System.out.println("Exception while getting the last download file :"
+ e.getMessage());
}
System.out.println("The last downloaded file is " + choice.getPath());
System.out.println("The last downloaded file is " + choice.getPath(),true);
return choice;
}

This will return the most recent created file, I made this because when you create a file in some situations, it may not always have the correct modified date.
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
private File lastFileCreated(String dir) {
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return true;
}
});
FileTime lastCreated = null;
File choice = null;
for (File file : files) {
BasicFileAttributes attr=null;
try {
attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}catch (Exception e){
System.out.println(e);
}
if(lastCreated ==null)
lastCreated = attr.creationTime();
if (attr!=null&&attr.creationTime().compareTo(lastCreated)==0) {
choice = file;
}
}
return choice;
}

Here's a small modification to Jose's code which makes sure the folder has at least 1 file in it. Work's great in my app!
public static File lastFileModified(String dir) {
File fl = new File(dir);
File choice = null;
if (fl.listFiles().length>0) {
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
long lastMod = Long.MIN_VALUE;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
}
return choice;
}

This code works for me well:
public String pickLatestFileFromDownloads() {
String currentUsersHomeDir = System.getProperty("user.home");
String downloadFolder = currentUsersHomeDir + File.separator + "Downloads" + File.separator;
File dir = new File(downloadFolder);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
testLogger.info("There is no file in the folder");
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
String k = lastModifiedFile.toString();
System.out.println(lastModifiedFile);
Path p = Paths.get(k);
String file = p.getFileName().toString();
return file;
}
//PostedBy: saurabh Gupta Aricent-provar

Related

Java - How to Open the Last Updated File From a Folder that is Sorted by last modified date?

I am trying to open a csv file from the download directory in Windows. Here is the algorithm:
Go to the download directory in Window
Sort directory based on the last modify date with last updated file at the top
Open the last updated file
Here is the code snippet that does #1 and # 2 (obtained from this link):
Code snippet is below:
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import java.io.File;
import java.util.Arrays;
public class FileSortingTest {
public static void main(String[] args) {
File dir = new File("C:\\Users\\user\\Downloads");
File[] files = dir.listFiles();
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
for (int i = 0; i < files.length; i++) {
File file = files[i];
System.out.printf("File %s - %2$tm %2$te,%2$tY%n= ", file.getName(),
file.lastModified());
}
}
How do I get the last updated file into a variable and then open the file to read using Excel?
I assume that if your Array is correctly sorted you could do something like this :
File lastUpdatedFile = files[0]
Process process = new ProcessBuilder("C:\\PathToExcel\\Excel.exe",lastUpdatedFile.getAbsolutePath()).start();
After exploring more in StackOverflow and this link regarding using the Desktop class the following I was able to use:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class OpenAFile2 {
public static void main(String[] args) throws IOException{
String userdir = System.getProperty("user.home");
String dirpath2 = userdir + "\\Downloads";
File fileName = getLatestFilefromDir(dirpath2);
System.out.println(fileName);
File file = fileName;
if(!Desktop.isDesktopSupported()){
System.out.println("Desktop is not supported");
return;
}
Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);
if(file.exists()) desktop.open(file);
}
private static File getLatestFilefromDir(String dirPath2){
File dir = new File(dirPath2);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}
}

How to search a file?

Supposedly the user will enter their "ID #: 1203103" then after that it will automatically create a text file named 1203103.txt. How can I search the file name "1203103.txt" in the file directory?
String id = scan.nextLine();
File file = new File(id+".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
System.out.println("Enter the ID # to search: ");
You can try with this.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:"); //file directory
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("1203103"); //here is you file name starts with. Or you can use name.equals("1203103.txt");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Hope this helps.
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID # to search: ")
String id=scan.next();
File f= new File(id+".txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("file exist");
}else{
System.out.println("file doesn't exist");
}
Your code will create a new file if the file doesn't already exist. If the file does exist, it will be erased and an empty file created in it's place. In both cases, you will have a brand new, empty file. There is nothing to search.
you can browse all files within a directory (a file) using list (for String results) or listfiles (for file results)...
String directoryName = ...;
File directory = new File(directoryName);
File[] listOfAllFiles = directory.listFiles();
String[] listOfAllFileNames = directory.list();
Try this to search through all the files in a directory:
for (File file : folder.listFiles()) {
if (!file.isDirectory())
System.out.println(file.getName()); //Match here
}
You don't need to search for it. You already know its name, so just need to check if it exists, and optionally if it's a file and not a directory:
File file = new File(fileName);
if (file.exists() && file.isFile()) {
// ...
}
Try this :
public static void main(String[] args) throws IOException {
String id = "kick";
File file = new File(id + ".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
File folder = new File("C:\\Users\\kick\\Documents\\NetBeansProjects\\JavaApplication191");
// the list of files at specified folder
File[] listOfFiles = folder.listFiles();
// go through the list of files to see if you can find file was named kick
for (int i = 0; i < listOfFiles.length; i++) {
// gives you access to each elements of listofFiles array name
String filename = listOfFiles[i].getName();
if (filename.startsWith("kick")) {
System.out.println("found");
} else{
System.out.println("not found');
}
}
}

Java renaming files in directory doesn't work properly

I am trying to rename to upper case all the files in a given directory. It does the whole thing but it doesn't do anything in the folder file names are still the same .
import java.io.File;
import java.io.IOException;
public class FileOps {
public static void main(String[] argv) throws IOException {
File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
File f = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files"
+ listOfFiles[i].getName());
f.renameTo(new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files"
+ listOfFiles[i].getName().toUpperCase()
+ ".txt"));
}
}
System.out.println("Done");
}
}
It prints "Done" in the console but nothing is really done
In your if statement, you forgot to add ending separator:
if (listOfFiles[i].isFile()) {
File f = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files\\"// <- Missing separator
+ listOfFiles[i].getName());
f.renameTo(new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files\\"// <- Missing separator
+ listOfFiles[i].getName().toUpperCase()
+ ".txt"));
}
A proper implemntation would be:
if (listOfFiles[i].isFile())
listOfFiles[i].renameTo(new File(folder, listOfFiles[i].getName().toUpperCase()+ ".txt"));//not sure why this .txt
Be careful, the renameTo method is highly platform dependent. Read the Javadoc
You might use the following to check what is happening. Some small changes include using the File(parent,name) form to avoid having to determine and add the OS specific file path separator.
package com.example.renaming;
import java.io.File;
import java.io.IOException;
public class TestRename {
private static final String[] defaultArgs = { "C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files" };
private static TestRename me;
private static String[] arguments;
public static void main(String[] args) {
me = new TestRename();
if (args == null | args.length == 0) {
arguments = defaultArgs;
} else {
arguments = args;
}
me.doWork(arguments);
}
private void doWork(String[] arguments) {
int numFiles = 0;
File folder = new File(arguments[0]);
try {
System.out.println("Working on " + folder.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File[] fileList = folder.listFiles();
if (fileList == null) {
System.out.println("No files fould");
} else {
for (int i = 0; i < fileList.length; i++) {
System.out.println("File " + fileList[i].getName());
if (fileList[i].isFile()) {
numFiles++;
try {
String currentName = fileList[i].getName();
File parent = fileList[i].getParentFile();
String newName = currentName.toUpperCase() + ".txt";
System.out.println(" .. current = " + currentName);
System.out.println(" .. newname = " + newName);
// Avoids having to get the file path separator for an OS
File newFile = new File(parent, newName);
System.out.println(" .. new File = "
+ newFile.getCanonicalPath());
fileList[i].renameTo(newFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("Done, found " + numFiles);
}
}
}
As pointed by ortis, you have missed to add "\" while naming files.
f.renameTo(new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files"
+ listOfFiles[i].getName().toUpperCase()
+ ".txt"));
executing this code over and over will result in adding .txt to the file names. You can consider using apache FileUtils for getting extention.
Making those changes to your code,
File folder = new File("/home/ubuntu/Desktop/pics");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles){
if(file.isFile()){
String fileName = FilenameUtils.removeExtension(file.getName()).toUpperCase() ;
String newPath = folder + File.separator + fileName+ "."+ FilenameUtils.getExtension(file.getName());
file.renameTo(new File(newPath));
}
}

Reading the java files from the folder

I have developed an application that reads files from the folder chosen by the user. It displays how many lines of code are in each file. I want only Java files to be shown in the file-chooser (files having .java extension). Below is my code:
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File dir, String name) {
return name.matches("\\*\\.java");
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
I have editied also but still it is not working please advise
please advise how to read only the files having .java as an extension in other words only java files from the folder ,please advise
You need a FilenameFilter. This should work for you:
FilenameFilter javaFileFilter= new FilenameFilter() {
#Override
public boolean accept(File logDir, String name) {
return name.endsWith(".java")
}
};
You should look upon Filtering the list of Files in JFileChooser.
It has an example of ImageFilter.java which shows only image files in file chooser.

Trying to delete files after concatenation with java

here is a code to concatenate all files from a folder.
it works well but i modified it to delete files after concatenation and this function is not working coze i don't know how to declare in main method
Any help will be appreciated thank you very much.
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Processing " + files[i].getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(files[i]
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
File directory = new File("C:/Target");
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
// Delete each file
if (!file.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+file);
}
}
}
}
First, make sure you have enough permission to be able to delete the contents in c:\target directory.
Second, if that directory contains subdirectories, you will need to delete all the files in each subdirectory first before you can perform a file.delete() on the subdirectory. You can do recursive deletion like this:-
public boolean deleteDirectory(File path) {
if (path.exists()) {
for (File file : path.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
file.delete();
}
}
}
return path.delete();
}
Then, you can call deleteDirectory("C:/Target"); to perform the recursive deletion.
I am guessing this is something you copied from elsewhere. You declare File[] files twice - the second time just do
File directory = new File("C:/Target");
// Get all files in directory
files = directory.listFiles();
for (File toDelete : files)
{
// Delete each file
if (!toDelete.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+toDelete);
}
}
You could try just moving your delete to your first loop... like this,
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File currentFile = files[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}

Categories