Get certain FileName based on its extension Java - java

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());
}

Related

Java code to get the list of file name from a folder

I have a scenario where around 5600 files are present.
I am able to retrieve the file names by using the below code:
String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; 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();
if (files.toLowerCase().endsWith(".xml"))
{
System.out.println(files);
}
, but i need only the first part For Eg:if the file name in folder is "abc_Transformed.xml" , i require only abc .. How to get it ?
You can use the substring method to find first string.
if (files.toLowerCase().endsWith(".xml"))
{
String result = files.substring(0, files.indexOf("_"));
System.out.println(result);
}
your whole code
String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; 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();
if (files.toLowerCase().endsWith(".xml"))
{
String result = files.substring(0, files.indexOf("_"));
System.out.println(result);
}
The information about the files is basically irrelevant. You are after some basic String manipulation functions.
You could try something using String.split() like:
String[] pieces = files.split("_");
String first = pieces[0]; // should be equal to "abc"
Or something using String.indexOf() and String.substr() like:
int indexOfUnderscore = files.indexOf("_");
String first = files.substr(0, indexOfUnderscore); // should be equal to "abc"
If you're new to Java, it's worth spending the time to review all the String functions.

find picture in folder withot extension

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);

Fix for type mismatch error " file to string "

In the below code im list the files from the folders and passing the filepath to the method loadCSV. But I am getting type mismatch error here. plz help
String Folderfilename= list[i];
can saying "cannot convert file to string"
File foldername = new File(filename);
System.out.println("actual"+foldername);
File[] list = foldername.listFiles();
for(int i=0; i<list.length; i++){
System.out.println("inside for" +list.length);
String substring = list[i].getName().substring(0, list[i].getName().indexOf("."));
System.out.println("substring" +substring);
if(list[i].isFile() && list[i].getName().contains(".csv")) {
////////getting mismatch error in the below line
String Folderfilename= list[i];
new SCLoad().loadCSV(con,Folderfilename, ImportTable);
System.out.println("CLASS NAME "+list[i]);
}
}
Here in the line
String Folderfilename= list[i];
but your list is a array of type File object.
So you cannot assign like that.Type mismatch is there.
May be you need getName().
String Folderfilename= list[i].getName();
Please add proper checks before using the above line.
I presume you are looking for files ending with csv. You should probably use a FileNameFilter. Here's a snippet
File dir = new File("/tmp/");
File[] csvFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("csv"); //get all csv files
}
});
//now load these csvFiles using whatever loaders
for (File csvFile : csvFiles) {
// I am guessing SCLoad requires a complete path.
new SCLoad().loadCSV(con,csvFile.getCanonicalPath(), ImportTable);
}
Do this
File file = list[i];
String Folderfilename= file.getName()
Two changes in your code:
list[i].getName();
and
if( list[i].isDirectory() ) continue; //to avoid exception and to keep looking for csv files.
String folderFileName = "";
File foldername = new File(filename);
File[] list = foldername.listFiles();
for(int i=0; i<list.length; i++){
if( list[i].isDirectory() )
continue;
folderFileName = list[i].getName();
if( folderFileName.toLowerCase().endsWith(".csv") ) {
System.out.println("csv file: " + folderFileName);
new SCLoad().loadCSV(con,folderFileName, ImportTable);
}
}

Expression Language in java

I have files in my directory like
/home/jay/120123.txt
/home/jay/121343.txt
/home/jay/122123.txt
The key here is first three digit of the file names is unique. How do i write expression language in java (never written EL in java) which will be same as unix command "ls 120*" = "120123.txt"
So something like String getFile(String uniqueId) this method will for instance be called as
String file = getFile("120") and the file should be 120123.txt
I need the logic for getFile() method
You want to use the File.listFiles(FilenameFilter).
Maybe in something like that:
public File[] getFiles(File folder, String prefix){
return folder.listFiles(new FilenameFilter(){
public boolean accept(File dir, String name){
return name.startsWith(prefix);
}
};
}
For Java 6
You may find the WildcardFileFilter in Apache Commons IO useful for this:
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("120*.txt");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
For Java 7
Files.newDirectoryStream offers this functionality:
Path dir = Paths.get(".");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "120*.txt")) {
for (Path entry : stream) {
System.out.println(entry.getFileName());
}
} catch (IOException e) {
}

Java: How to read directory folder, count and display no of files and copy to another folder?

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;
}

Categories

Resources