Java check directory for zip files - java

I have the below code which checks to see if folder exists on the sdcard, I would like to add another if statement if the folder exists to check that there are zip files inside the actual folder if it in fact exists. What could i do to check the folder for a zip extension. The folder should have a lot of zips in it but i only want it to check to make sure there are zips and no other file extension. I thank you for any help with this.
File z = new File("/mnt/sdcard/folder");
if(!z.exists()) {
Toast.makeText(MainMethod.this, "/sdcard/folder Not Found!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainMethod.this, "/sdcard/folder Found!", Toast.LENGTH_LONG).show();
}
EDIT:
Thanks guys for the help here is what i ended up using with your help, i haven't tested it yet but it looks good to me.
File z = new File("/mnt/sdcard/Folder");
if(!z.exists()) {
//create folder
} else {
FilenameFilter f2 = new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith("zip");
}
};
if (z.list(f2).length > 0) {
// there's a zip file in there..
} else {
//no zips inside folder
}
}

File f = new File("folder");
FilenameFilter f2 = new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith("zip");
}
};
if (f.list(f2).length > 0) {
// there's a zip file in there..
}
Try the above..

Have you looked at FileNameFilter ?
File f = new File("/mnt/sdcard/folder");
if(e.exist()){//file exist ??
File[] matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith("zip");
}
});//list out files with zip at the end
}

Related

Java, know if a file is inside a folder

Hi guys I'm trying to find if a specific file is inside the project directory.
File f = new File(System.getProperty("user.dir"));
System.out.println(f);
String archivoLiga="LigaV2";
System.out.println(f.listFiles((dir1, name) -> name.startsWith(archivoLiga) && name.endsWith(".properties")).length == 0);
But this only works if the file is in the "first" level, i want it to find it even if it's inside another folder. Any ideas?
Use Java 8's find() method to recurse subdirectories:
final int MAX_DEPTH = 50; // Max depth of subdirectories to search
Path userDir = Paths.get(System.getProperty("user.dir"));
System.out.println(userDir);
String archivoLiga="LigaV2";
System.out.println(
Files.find(
userDir,
maxDepth,
(path,attr) -> path.getFileName().startsWith(archivoLiga)
&& path.getFileName().endsWith(".properties"))
.findAny()
.isPresent());
Try recursively looking inside subfolders :-
public boolean checkForFile(String dirname,String prefix,String ext){
File dir = new File(dirname);
//System.out.println(dir);
for(File f : dir.listFiles()){
if(f.isFile()){
if(f.getName().startsWith(prefix) && f.getName().endsWith(ext)){
System.out.println(f.getName());
return true;
}
}
else{
//This step starts looking inside subfolder as well
return checkForFile(f.getAbsolutePath(),prefix,ext);
}
}
return true;
}
To check a file inside a folder, You will need to use exists() method of java.io.File like this:
boolean exists = new File("FOLDER_PATH/FILE_NAME").exists();
if (exists) {
System.out.println("File exists inside given folder");
} else {
System.out.println("File does not exists inside given folder");
}
Also possible with FileVisitor:
#Getter #Setter
#RequiredArgsConstructor
public static class SearchVisitor extends SimpleFileVisitor<Path> {
private final String fileToSearch;
private boolean found=false;
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(!file.getFileName().toString().equals(fileToSearch)) return FileVisitResult.CONTINUE;
found=true;
return FileVisitResult.TERMINATE;
}
}
public void test() throws IOException {
SearchVisitor sv = new SearchVisitor("LigaV2");
Files.walkFileTree( Paths.get(System.getProperty("user.dir")), sv);
log.info("found file {}:{}", sv.getFileToSearch(), sv.isFound());
}
Use public boolean isDirectory() in java file API following is the link to oracle documentation. Tests whether the file denoted by this abstract pathname is a directory.
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()

ITreeContentProvider - How to filter files while still showing parent folder?

I am currently trying to implement a SWT CheckBoxTreeViewer for my project. However, I am currently running into some problems with the file filtering.
I want my tree to show all files in a directory (including subdirectories) with a specific file extension (such as "txt") as well as their parent folders.
For example:
parentA
childA1.txt
childA2.txt
parentB
childB1.txt
However, I can't figure out a way how to do this. I've tried several ways of coding the FileFilter as follows:
class FileTreeContentProvider implements ITreeContentProvider {
public Object[] getChildren(Object arg0) {
return ((File) arg0).listFiles();
}
public Object getParent(Object arg0) {
return ((File) arg0).getParentFile();
}
public boolean hasChildren(Object arg0) {
Object[] obj = getChildren(arg0);
return obj == null ? false : obj.length > 0;
}
...
1)
...
public Object[] getElements(Object arg0) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
File workspaceDirectory = workspace.getRoot().getLocation().toFile();
String[] extension = new String[] {"txt"};
Collection<File> files = FileUtils.listFiles(workspaceDirectory, extension, true);
File[] files2 = new File[files.size()];
int i = 0;
for(File file : files) {
files2[i] = file;
i++;
}
return files2;
}
...
}
The problem with this is that it only shows the files with the file extension but not its parent directories.
For example:
childA1.txt
childA2.txt
childB1.txt
2)
...
public Object[] getElements(Object arg0) {
IWorkspace workspace = ResourcesPlugin.getWorkspace();
File workspaceDirectory = workspace.getRoot().getLocation().toFile();
return workspaceDirectory.listFiles(new FilenameFilter() {
#Override
public boolean accept(File workspaceDirectory, String name) {
if (workspaceDirectory.getName().startsWith(".") {
return false;
}
else {
return true;
}
}
});
}
...
}
This snippet removes the folders starting with "." in the root directory, but does not remove the files starting with "." in the subdirectories. Therefore, I got something like this:
parentA
.project
.settings
childA1.txt
childA2.txt
...
Also, as it does not explicitly filter in just files ending in "txt", if I were to put other file types in the workspace folder I would also see those files in the tree which is not something I want.
Is there anyway to fix this? I am using Eclipse Mars 4.5.1.

How to check if a folder exists?

I am playing a bit with the new Java 7 IO features. Actually I am trying to retrieve all the XML files in a folder. However this throws an exception when the folder does not exist. How can I check if the folder exists using the new IO?
public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
Using java.nio.file.Files:
Path path = ...;
if (Files.exists(path)) {
// ...
}
You can optionally pass this method LinkOption values:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
There's also a method notExists:
if (Files.notExists(path)) {
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
To check if a directory exists with the new IO:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.
See: documentation.
Generate a file from the string of your folder directory
String path="Folder directory";
File file = new File(path);
and use method exist.
If you want to generate the folder you sould use mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
You need to transform your Path into a File and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
We can check files and thire Folders.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.
The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.
The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.
Noncompliant Code Example:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
Compliant Solution:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}

How do I import a directory (and subdirectory) listing in Java?

Here is the code I have thus far:
import java.io.*;
class JAVAFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".java"));
}
}
public class tester {
public static void main(String args[])
{
FilenameFilter filter = new JAVAFilter();
File directory = new File("C:\\1.3\\");
String filename[] = directory.list(filter);
}
}
At this point, it'll store a list of all the *.java files from the directory C:\1.3\ in the string array filename. However, i'd like to store a list of all the java files also in subdirectories (preferably with their path within C:\1.3\ specified also. How do I go about doing this? Thanks!
you should look at DirectoryWalker from Apache
I'm afraid you can't do it with the list(FilenameFilter) method. You'll have to list all files and directories, and then do the filtering yourself. Something like this:
public List<File> getFiles(File dir, FilenameFilter filter) {
List<File> ret = new ArrayList<File>();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
ret.addAll(getFiles(f, filter));
} else if (filter.accept(dir, f.getName())) {
ret.add(f);
}
}
return ret;
}
As far as I know, you will have to do this manually (recursively), i.e. you will have to call list(filter) for all sub-directories of C:\1.3\, and so on....

Can I compile anonymous or inner classes into a single java .class file?

I am writing a Java class that parses log files. The compiled .class file needs to be loaded into a 3rd party monitoring platform (eG) for deployment and invocation. Unfortunately, the 3rd party platform only allows me to upload a single .class file.
My current implementation has a function to find the 'latest' file in a folder that conforms to a file mask (*CJL*.log) and uses 2 anonymous classes, one to filter a directory listing and another to sort a list of files based on ModifiedDt. When I compile this, I get 3 .class files (Monitor.class, Monitor$1.class, Monitor$2.class) which I cannot deploy.
Is it possible to compile the anonymous classes into a single .class file for deployment to the 3rd party monitoring platform?
I have attached the code of my 'Find Lastest file' function for illustration.
private String FindLatestFile(String folderPath) {
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.endsWith(".log")
& name.contains("CJL"))
return true;
else
return false;
}
};
File dir = new File(folderPath);
File[] files = dir.listFiles(filter);
if (files.length > 0) {
Arrays.sort(files, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(
f2.lastModified());
}
});
File newest = files[files.length - 1];
return newest.toString;
} else {
return "";
}
}
I suppose it is possible to do this the 'dumb' way by getting a raw file listing and doing the filter/sort myself but I'm worried this will not be performant.
Any Ideas?
Michael
No its not possible afaik. I assume a jar also cannot be used.
A workaround would be to have the class implement the two interfaces to remove the need for the inner classes.
class MyClass implements FilenameFilter, Comparator<File> {
...
public boolean accept(File dir, String name) {
if (name.endsWith(".log") & name.contains("CJL"))
return true;
else
return false;
}
public int compare(File f1, File f2) {
return Long.valueOf(f1.lastModified()).compareTo(
f2.lastModified());
}
private String FindLatestFile(String folderPath) {
File dir = new File(folderPath);
File[] files = dir.listFiles(this);
if (files.length > 0) {
Arrays.sort(files, this);
File newest = files[files.length - 1];
return newest.toString;
} else {
return "";
}
}

Categories

Resources