how can I get all files in folder only by name without extension file?
for example I have picture name "pic1" and I don't know extension it can be "gif","jpeg","png"
I tried that but it's also looking for extension:
File dir = new File("...");
String[] files = dir.list(new NameFileFilter("pic1"));
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
thank,
String[] files = dir.list(new FilenameFilter() {
#Override
boolean accept(File dir, String name) {
//return name.startsWith("pic1.");
return name.matches("(?i)pic1\\.(gif|jpg|jpeg|png)");
}
});
Java 8:
String[] files = dir.list((dir, name) -> name.startsWith("pic1."));
List the files without providing a filter, then loop on the list: if fileNameString.startsWith("pic1") then do your logic.
To do this more correctly, use FilenameUtils.removeExtension() from Apache Commons IO (on the file name).
Since you're already using the Apache library, try:
FileFilter fileFilter = new WildcardFileFilter("pic1.*");
String[] files = dir.list(fileFilter);
Related
Hello I am trying to retrieve the names of all the files of the type .mp3 from a source folder(below)
Below is the code I am using to differentiate the file type and add to the list. However I do not know which parameter I should enter into the directory it should be music folder however I do not know how to represent this.
File dir = new File("");
String[] files = dir.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".mp3");
};
});
for(int a = 0; a < files.length; a++)
{
musicList.add(files[a]);
}
Try this.
List<String> result = Files.find(Paths.get("music"), 100,
(p, a) -> p.toString().toLowerCase().endsWith(".mp3"))
.map(path -> path.toString())
.collect(Collectors.toList());
if you are using Servlet :
ServletActionContext.getServletContext().getRealPath("music");
if using Spring :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("music").getFile());
System.out.println(file.getAbsolutePath());
For javafx see this:
How to target a file (a path to it) in Java/JavaFX
I want to get certain file from my path which is only with ".pdf" file . How can i achieve it ?
File path = new File("C:\\Users\\theunique\\Documents\\NetBeansProjects\\APUassignment");
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i].getName());
}
}
my output result is
ModulesNumber.txt
ModulesObjects.dat
number.txt
Objects.dat
OODJ-Exam-Nick.pdf
oodj-null-Joseph.pdf
I want it to be
OODJ-Exam-Nick
OODJ-null-Joseph
For this purpose you could use the Apache Commons IO.
String fileExtension = FilenameUtils.getExtension(files[i]);
String fileNameWithoutExtension = FilenameUtils.removeExtension(files[i]);
if(fileExtension.equals("pdf")){
System.out.println(fileNameWithoutExtension);
}
int index = files[i].getName().lastIndexOf(".");
String extension= files[i].getName().substring(index, files[i].getName().length());
if(extension.equalsIgnoreCase("pdf") {
System.out.println(files[i].getName().subString(0, index));
}
You can use File.listFiles(FilenameFilter).
See Use of FilenameFilter.
File[] files = path.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
// Automatically weeds out directories
return name.toLowerCase().endsWith(".pdf");
}
});
// Why use an index?
for (File file : files) {
System.out.println(file.getName());
}
I need to know how to know how to make Java's File.list(); method list only the files I am able to access or how to filter them out, cause now it lists files like $RecycleBin or Documents and Settings (I am on Win7) basically files I am unable to see in Win Explorer. Many Thanks.
The following will do it:
File[] subDirs = dir.listFiles( new FileFilter() {
#Override public boolean accept( File f ) {
return f.canWrite();
} } );
You could also use CanWriteFileFilter of apache.commons.io (http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/filefilter/CanWriteFileFilter.html)
Example, showing how to print out a list of the current directory's writable files:
File dir = new File(".");
String[] files = dir.list( CanWriteFileFilter.CAN_WRITE );
for ( int i = 0; i < files.length; i++ ) {
System.out.println(files[i]);
}
public class Sorter {
String dir1 = ("C:/Users/Drew/Desktop/test");
String dir2 = ("C:/Users/Drew/Desktop/");
public void SortingAlgo() throws IOException {
// Declare files for moving
File sourceDir = new File(dir1);
File destDir = new File(dir2);
//Get files, list them, grab only mp3 out of the pack, and sort
File[] listOfFiles = sourceDir.listFiles();
if(sourceDir.isDirectory()) {
for(int i = 0; i < listOfFiles.length; i++) {
//list Files
System.out.println(listOfFiles[i]);
String ext = FilenameUtils.getExtension(dir1);
System.out.println(ext);
}
}
}
}
I am trying to filter out only .mp3's in my program. I'm obviously a beginner and tried copying some things off of Google and this website. How can I set a directory (sourceDir) and move those filtered files to it's own folder?
File provides an ability to filter the file list as it's begin generated.
File[] listOfFiles = sourceDir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".mp3");
}
});
Now, this has a number of benefits, the chief among which is you don't need to post-process the list, again, or have two lists in memory at the same time.
It also provides pluggable capabilities. You could create a MP3FileFilter class for instance and re-use it.
I find the NIO.2 approach using GLOBs or custom filter the cleanest solution. Check out this example on how to use GLOB or filter example in the attached link:
Path directoryPath = Paths.get("C:", "Program Files/Java/jdk1.7.0_40/src/java/nio/file");
if (Files.isDirectory(directoryPath)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(directoryPath, "*.mp3")) {
for (Path path : stream) {
System.out.println(path);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
For more information about content listing and directory filtering visit Listing and filtering directory contents in NIO.2
if(ext.endWith(".mp3")){
//do what ever you want
}
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;
}