I want to get a list of all files recently open or created, i.e. all the files in the Windows "recent folder" .
I can't find any solutions, I tried shgetfolderpath, windows registry but nothing worked. How can I get access to all files in the recent folder using Java?
Try this code in java :
File file = new File("Windows/Recent/Folder/Path");
if (file.exists() && file.isDirectory()) {
File[] listFiles = file.listFiles();
for (File files : listFiles) {
if(files.isDirectory()) {
System.out.println(files.getAbsolutePath() + " - Directory");
}else {
System.out.println(files.getAbsolutePath() + " - File");
}
}
}
Hope this will help you, try this out:
import java.io.File;
public class ListFiles
{
public static void main(String[] args)
{
// Directory path here
String path = "F:\\Book"; // the directory you want to search
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);// with out printing you can add the names of file in array
}
}
}
}
Related
i am trying to copy the contents of a last modified file from a folder to the other folder using java
i am able to move the file but i am unable to move the contents of the file
private File getLatestFilefromDir(String dirPath) throws IOException{
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];
}
}
String newFilePath = "C:\\newPath\\"+lastModifiedFile.getName();
Path temp = Files.move
(Paths.get(dirPath),
Paths.get(newFilePath ));
if(temp != null)
{
System.out.println("File renamed and moved successfully");
}
else
{
System.out.println("Failed to move the file");
}
return new File(newFilePath );
}
Result : only file is moving but not contents
Rather use the Apache Commons IO library and more specifically org.apache.commons.io.FileUtils. It's a very nice library that works really well with what your trying to do.
File sourceFile = new File(...);
File destinationFile = new File(...);
FileUtils.moveFile(sourceFile, destinationFile);
Used it quite successfully on a small project I did a while back (FilingAssistant)
I'm trying to loop through a folder and list all files with a specific file ending. I'm trying to solve this problem with a recursive method but I'm not getting anywhere.
private int counter = 0;
public void printAllJavaFiles(File directory) {
printFile(directory);
File[] subDirectories = directory.listFiles();
for (File file : subDirectories) {
printAllJavaFiles(file);
}
}
private void printFile(File file) {
// Get file extension
String fileExtension = "";
int i = file.getName().lastIndexOf('.');
if (i >= 0) {
fileExtension = file.getName().substring(i + 1);
}
if (fileExtension.equals("java")) {
System.out.println("File: " + file.getName() + " Size: " + file.length());
}
}
Any suggestions? I really have no idea how to go up and down in the directory structure. It just enters the first folder and once it's done listing it's files it throws a nullpointerexception.
You should use the File.isDirectory() method. Like this:
public void printAllJavaFiles(File directory) {
if (directory.isDirectory()) {
File[] subDirectories = directory.listFiles();
for (File file : subDirectories) {
printAllJavaFiles(file);
}
}else {
printFile(directory);
}
}
Documentation on that method here: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()
The idea is that for every file you check if it is a folder, if so, make the recursive call. If not, simply print the file.
Am writing a Jenkins Groovy script file to get all the .NET project solution files (*.sln) in a given directory (including subdirectories).
First I tried to get the list of directories in a given path. I used the below code which is working fine:
File folder = new File("D:\\Data");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
println("File " + listOfFiles[i].getName());
}
else if (listOfFiles[i].isDirectory()) {
println("Directory " + listOfFiles[i].getName());
}
}
2) When modified the code as below to list out all the solution files in a given path I am getting error:
File folder = new File("D:\\Data");
File[] listOfFiles = folder.listFiles();
Collection files = FileUtils.listFiles(
folder,
new RegexFileFilter("^(*.sln)"),
DirectoryFileFilter.DIRECTORY
);
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
println("File " + files[i].getName());
}
else if (files[i].isDirectory()) {
println("Directory " + files[i].getName());
}
}
Error details:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 5: unable to resolve class RegexFileFilter
# line 5, column 3.
new RegexFileFilter("^(*.sln)"),
^
Could anyone please help me on this to get all the solution files in a given path (including subdirectories)
Thanks in advance!!
Simples solution is to use FileNameFinder like this:
def finder = new FileNameFinder()
def files = finder.getFileNames 'D:\\Data', '**/*.sln'
print files
This should do it
import static groovy.io.FileType.*
def startDir = new File("D:\\Data")
startDir.eachFileRecurse(FILES) {
if (it.name.endsWith('.sln')) {
println it
}
}
so I have this program where I want to get the current list of files in the directory where the Java file is executing.
Here is the call:
File q1 = new File(System.getProperty("user.dir"));
File[] listOfFiles = sanitiseFileChecker(q1.listFiles());
And this is the sanitiseFileChecker method:
public void sanitiseFileChecker(File[] list){
List<File> files = new ArrayList<File>(Arrays.asList(list));
for(int i = 0; i < files.size(); i++){
System.out.println(files.get(i).getName());
}
}
This works perfectly except... my output is
Name.class
FOLDER
FILEA
FILEB
FILEC
But Name.java does not appear... I am confused why it is not being detected, can Java not detect a file listing when a java program is running?
This worked like expected to me:
import java.io.*;
public class ShowFiles {
public static void main(String[] args) {
File userDir = new File(System.getProperty("user.dir"));
File[] files = userDir.listFiles();
System.out.println("Files in " + userDir.getAbsolutePath());
for (File file : files) {
System.out.println("\t" + file.getName());
}
}
}
Sorry guys, my fault, I realised a mistake with concurrent removal from the list itself which caused the indexes to get mixed up.
I have to read a folder, count the number of files in the folder (can be of any type), display the number of files and then copy all the files to another folder (specified).
How would I proceed?
i Have to read a folder, count the number of files in the folder (can
be of any type) display the number of files
You can find all of this functionality in the javadocs for java.io.File
and then copy all the files to another folder (specified)
This is a bit more tricky. Read: Java Tutorial > Reading, Writing and Creating of Files
(note that the mechanisms described there are only available in Java 7 or later. If Java 7 is not an option, refer to one of many previous similar questions, e.g. this one: Fastest way to write to file? )
you have all the sample code here :
http://www.exampledepot.com
http://www.exampledepot.com/egs/java.io/GetFiles.html
File dir = new File("directoryName");
String[] children = dir.list();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
for (int i=0; i<children.length; i++) {
// Get filename of file or directory
String filename = children[i];
}
}
// It is also possible to filter the list of returned files.
// This example does not return any files that start with `.'.
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
};
children = dir.list(filter);
// The list of files can also be retrieved as File objects
File[] files = dir.listFiles();
// This filter only returns directories
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
files = dir.listFiles(fileFilter);
The copying http://www.exampledepot.com/egs/java.io/CopyDir.html :
// Copies all files under srcDir to dstDir.
// If dstDir does not exist, it will be created.
public void copyDirectory(File srcDir, File dstDir) throws IOException {
if (srcDir.isDirectory()) {
if (!dstDir.exists()) {
dstDir.mkdir();
}
String[] children = srcDir.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(srcDir, children[i]),
new File(dstDir, children[i]));
}
} else {
// This method is implemented in Copying a File
copyFile(srcDir, dstDir);
}
}
However is very easy to gooole for this stuff :)
I know this is too late but below code worked for me. It basically iterates through each file in directory, if found file is a directory then it makes recursive call. It only gives files count in a directory.
public static int noOfFilesInDirectory(File directory) {
int noOfFiles = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
noOfFiles++;
}
if (file.isDirectory()) {
noOfFiles += noOfFilesInDirectory(file);
}
}
return noOfFiles;
}