I am looking a way to get the list of files inside a zip file. I created a method to get the list of files inside a directory but I am also looking a way to get files inside a zip as well instead of showing just zip file.
here is my method:
public ArrayList<String> listFiles(File f, String min, String max) {
try {
// parse input strings into date format
Date minDate = sdf.parse(min);
Date maxDate = sdf.parse(max);
//
File[] list = f.listFiles();
for (File file : list) {
double bytes = file.length();
double kilobytes = (bytes / 1024);
if (file.isFile()) {
String fileDateString = sdf.format(file.lastModified());
Date fileDate = sdf.parse(fileDateString);
if (fileDate.after(minDate) && fileDate.before(maxDate)) {
lss.add("'" + file.getAbsolutePath() +
"'" + " Size KB:" + kilobytes + " Last Modified: " +
sdf.format(file.lastModified()));
}
} else if (file.isDirectory()) {
listFiles(file.getAbsoluteFile(), min, max);
}
}
} catch (Exception e) {
e.getMessage();
}
return lss;
}
After having searched for a better answer for a while, I finally found a better way to do this. You can actually do the same thing in a more generic way using the Java NIO API (Since Java 7).
// this is the URI of the Zip file itself
URI zipUri = ...;
FileSystem zipFs = FileSystems.newFileSystem(zipUri, Collections.emptyMap());
// The path within the zip file you want to start from
Path root = zipFs.getPath("/");
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
// You can do anything you want with the path here
System.out.println(path);
// the BasicFileAttributes object has lots of useful meta data
// like file size, last modified date, etc...
return FileVisitResult.CONTINUE;
}
// The FileVisitor interface has more methods that
// are useful for handling directories.
});
This approach has the advantage that you can travers ANY file system this way: your normal windows or Unix filesystem, the file system contain contained within a zip or a jar, or any other really.
You can then trivially read the contents of any Path via the Files class, using methods like Files.copy(), File.readAllLines(), File.readAllBytes(), etc...
You can use ZipFile.entries() method to read the list of files via iteration as below:
File[] fList = directory.listFiles();
for (File file : fList)
{
ZipFile myZipFile = new ZipFile(fList.getName());
Enumeration zipEntries = myZipFile.entries();
while (zipEntries.hasMoreElements())
{
System.out.println(((ZipEntry) zipEntries.nextElement()).getName());
// you can do what ever you want on each zip file
}
}
Related
I am developing a java application to perform operations with files.
In particular, I perform move and copy of files .. and I have programmed two functions.
Functions take strings such as sourcePath and targetPath as parameters.
I am developing on a mac, and I have given 777 permissions to the folders I need.
But I have the problem, that when I pass paths to the copyFile and moveFile functions I lose the last "/" of the path and consequently get a java.nio.File: NoSuchFileException exception.
I have read both the Java and online documentation but have not found any answers.
I accept any suggestion or advice ... I just add that by manually forcing the path inside the function, then not passing sourcePath and targetPath, the two functions behave as they should.
copyFile:
public static boolean copyFile(String sourcePath, String targetPath) throws IOException {
boolean fileCopied = true;
// if i pass sourcePath i lost the last /
File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
File[] listOfFiles = dirFiles.listFiles();
String dest = "/Users/myname/Documents/deleghe/local/F24_CT/deleghe_da_inviare_a_icbpi/";
for (File file : listOfFiles) {
Files.copy(file.toPath(),
(new File(dest + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
return fileCopied;
}
moveFile:
public static boolean moveFile(String sourcePath, String targetPath) throws IOException {
boolean fileMoved = true;
// if i pass sourcePath i lost the last /
File dirFiles = new File("/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_da_inviare_a_icbpi/");
File[] listOfFiles = dirFiles.listFiles();
String dest = "/Users/myname/Documents/deleghe/remote/F24_CT/deleghe_inviate/";
for (File file : listOfFiles) {
if (file.length() >= 968 && file.length() <= 2057) {
Files.move(file.toPath(),
(new File(dest + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("File spostato correttamente: " + file.getName() + "!! \n");
} else {
System.out.println("Non รจ stato possibile spostare il file: " + file.getName() + "!! \n");
}
}
return fileMoved;
}
try to use Paths.get(dest, file.getName()).toUri() instead of dest + file.getName() (it is not best practice)
you are not losing anything, you just reading files from directory and your code is working without any exception. Check your directories and files inside them one more time
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.
I'm writing a program that does various data analysis functions for use with Excel.
I need a way of returning file names of documents so I can search through them and find the ones I want.
I need to be able to take a string, saved as a variable, and use it to return the name of every document in a folder whose file name contains that string.
This will be used to sift through pre-categorized sections of data. Ideally I would save those documents' file names in a string array for later use within other functions.
private List<String> searchForFileNameContainingSubstring( String substring )
{
//This is assuming you pass in the substring from input.
File file = new File("C:/Users/example/Desktop"); //Change this to the directory you want to search in.
List<String> filesContainingSubstring = new ArrayList<String>();
if( file.exists() && file.isDirectory() )
{
String[] files = file.list(); //get the files in String format.
for( String fileName : files )
{
if( fileName.contains( substring ) )
filesContainingSubstring.add( fileName );
}
}
for( String fileName : filesContainingSubstring )
{
System.out.println( fileName ); //or do other operation
}
return filesContainingSubstring; //return the list of filenames containing substring.
}
Using this method, you could pass in the input from the user as the string you want the filename to contain. The only other thing you need to change is where you want in your directory to start searching for files, and this program only looks in that directory.
You could further look recursively within other directories from the starting point, but I won't add that functionality here. You should definitely look into it though.
This also assumes that you are looking for everything within the directory, including other folders and not just files.
You can get the list of all the files in a directory and then store them in an array. Next, using the java.io.File.getName() method, you can get the names of the files. Now you can simply use the .indexOf() method to check whether the string is a substring of the file name. I assume that all the items in the directory of concern are files and not sub directories.
public static void main(String[] args) throws IOException {
File[] files = new File("X:/").listFiles(); //X is the directory
String s <--- the string you want to check filenames with
for(File f : files){
if(f.getName().toLowerCase().indexOf(s.toLowerCase()) != -1)
System.out.println(f.getName());
}
}
This should display the names of all those files in the directory X:\ whose names include the String s.
References
This question: How do I iterate through the files in a directory in Java?
The java.io.File.getName() method
Statutory edit info
I have edited this answer simply to replace the previous algorithm, for checking the existence of a substring in a string, with the one that is currently used in the code above.
Here is an answer to search the file recursively??
String name; //to hold the search file name
public String listFolder(File dir) {
int flag;
File[] subDirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
System.out.println("File of Directory: " + dir.getAbsolutePath());
flag = Listfile(dir);
if (flag == 0) {
System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
return dir.getAbsolutePath();
}
for (File folder : subDirs) {
listFolder(folder);
}
return null;
}
private int Listfile(File dir) {
boolean ch = false;
File[] files = dir.listFiles();
for (File file : files) {
Listfile(file);
if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
System.out.println(name + "Found Sucessfully!!");
ch = true;
}
}
if (ch) {
return 1;
} else {
return 0;
}
}
I'm curious as if there's a way to define a Parent-folder, then have a program cycle through all of the files, and sub-folders, and rename the file extension.
I know this can be done in the command prompt using the command "*.ext *.newext" however that's not a possible solution for me and I need to rename 2,719 file extentions that are nested inside of this folder.
Yes, you can do it. Here's an example:
// java 6
File parentDir = new File("..");
System.out.println(parentDir.getAbsolutePath());
final File[] files = parentDir.listFiles();
System.out.println(Arrays.toString(files));
// java 7+
File parentDir = new File("..");
try {
Files.walkFileTree(parentDir.toPath(), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toFile().renameTo(new File("othername.txt"))) {
return FileVisitResult.CONTINUE;
} else {
return FileVisitResult.TERMINATE;
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
This one does not go through subdirs, but it is easy to modify that way.
Here's a simple function that should do the job for you. Sorry, if it's not the most elegant code -- my Java is a little rusty.
By default, it's recursive in its implementation; so be aware that it will affect all files of the specified type in the parent directory!
SwapFileExt params
path the parent directory you want to parse
cExt the extension type that you want to replace
nExt the desired extension type
NOTE: Both cExt and nExt are to be represented without the '.' (e.g. "txt", not ".txt")
public static void SwapFileExt(String path, String cExt, String nExt) {
File parentDir = new File(path);
File[] contents = parentDir.listFiles();
for (int i = 0; i < contents.length; i++) {
if (contents[i].isFile()) {
if (contents[i].toString().contains("." + cExt)) {
String item = contents[i].toString().replaceAll("." + cExt, "." + nExt);
contents[i].renameTo(new File(item));
}
} else if (contents[i].isDirectory()) {
SwapFileExt(contents[i].toString(), cExt, nExt);
}
}
}
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;
}