Java: one-liner to list Dirs in a directory? - java

One-Liner to list TXT-files.
import java.io.File;
import java.io.FilenameFilter;
...
files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
}
);
Source.
Is there an one-liner to list dirs in a dir?

public static void main (String[] args) throws Exception {
File dir = new File("yourDir");
FileFilter fileFilter = new FileFilter() {
public boolean accept(File file) {
return file.isDirectory();
}
};
File[] files = dir.listFiles(fileFilter);
for (File f : files)
System.out.println( f.getName() );
}

This uses Commons IO, but really is the simplest way to list all the directory names. It also has a way more powerful set of filters that you can use for other purposes:
String[] dirNames = new File("/Users/jonathan").list(DirectoryFileFilter.INSTANCE);
for (String dirName: dirNames)
System.out.println("Directory Name: " + dirName);

import java.io.File;
import java.io.FileFilter;
...
files = dir.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
Note the use of listFiles(FileFilter) rather than listFiles(FilenameFilter).

You will need to import java.nio.file.Files and java.nio.file.Paths, which are available since Java 1.7. Then using streams, which were introduced in Java 1.8, you can do something like the following:
Files.list(Paths.get(".")).filter(x -> Files.isDirectory(x)).forEach(System.out::println);
This gets files in the current directory ".", lists them, and filters them so only directories are included, then iterates over the directories stream to print them out using a println method reference.
Actually you could use a method reference for the filter as well like so:
Files.list(Paths.get(".")).filter(Files::isDirectory).forEach(System.out::println);

Related

Regex to replace a folder name in poll path in java

I have a relative path to get the files listed in that folder:
folder name: ReadFiles
I just use File pollFile = new File("ReadFiles") to read all the files from that folder.
Now the folder becomes "ReadFiles/201907101418" and folder name with date range varies all the time.
Is there any way to use regular expression to replace that date specific folder and get all the files listen under it?
You can use a FileFilter to check the name of subfolders to match with a pattern:
package be.test;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) throws IOException {
File f=new File("ReadFiles");
File[] datefolders=f.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory() && pathname.getName().matches("20\\d{10}");
}
});
for (File subf:datefolders)
{
File[] myfiles=subf.listFiles();
for (File myfile:myfiles)
{
System.out.println("Found file: "+myfile.getAbsolutePath());
// do your stuff with the files in myfile;
}
}
}
}

How do I add all the filenames under a certain folder to an arraylist using Java

I have this much so far
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import org.pdfbox.util.Splitter;
public class fileName {
public static void main(String args[]){
File file = new File("/Users/apple/Desktop/");
String[] directories = file.list(new FilenameFilter(){
#Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
System.out.println(Arrays.toString(directories));
ArrayList<String[]>SSOList = new ArrayList<String[]>();
}
}
It prints the names of all the files on my desktop but I want to add them to an arraylist. How do I do that?
It is very easy. You can use recursion as follows:
private static void read(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
read(fileEntry);
} else {
//Do something
}
}
}
There are quite a few ways by which you can get the filenames in an ArrayList:
Use the Arrays.asList() method:
ArrayList<String> SSOList = new ArrayList<String>(Arrays.asList(directories));
Use the Collections utility class allAll method:
List<String> SSOList = new ArrayList<String>(directories.length);
Collections.addAll(SSOList , directories);
Traverse the directories array again and add each value to the ArrayList SSOList.
Kepping in mind that these are to be done after you get the values in directories array.
ArrayList<String> SSOList = new ArrayList<String>(Arrays.asList(directories))
or you can use:
Collections.addAll(SSOList, directories);
Also if SSOList is the name of the ArrayList you want the files to be stored in, I think you need to change it to an array list of Strings and not array list of array of Strings :
List<String>SSOList = new ArrayList<String>();

Search for file in a directory and its sub-directories [duplicate]

This question already has answers here:
Recursively find all text files in directory
(3 answers)
Closed 8 years ago.
I would like to search all .txt files in a directory and its sub-directories. This is what I so far.
package com.gm.scratchpad;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static List<File> digFiles(File root, String typeOfFiles) {
ArrayList<File> files = new ArrayList<File>();
File[] files1 = root.listFiles();
return Arrays.asList(files1);
}
public static void main(String[] args) {
System.out.println("Hey, here are the files we dug!");
System.out.println(digFiles(new File("C:/development/scratchpad/test/vinvRoot"),null));
}
}
I suggest you use File.walkFileTree. See here for a description of how to use it.
I am not going to give you actual code. Here is a pseudo-code that should help. It is the most naive way of implementing. You should be able to improve it once you know how to implement:
List<File> findFiles(File directoryToSearch, String fileType) {
List<File> result = ...;
for each entry in directoryToSearch{
if (entry is a directory) {
result.addAll(findFiles(entry, fileType));
} else if (entry is a file and entry is of fileType) {
result.add(entry);
}
}
return result;
}
Actually recursive directory walking is common and there is already a lot of utilities that can help.

Files.copy throws java.nio.file.NoSuchFileException even though the file to be copied definitely exists

I have a problem with a seemingly simple application.
What it should do:
-Read out the files (*.jpg) of a (hardcoded) directory
-Use the contained Metadata (gotten via implemented Libraries) of said jpgs to generate directories (./year/month/)
-copy the files into the corresponding directories.
What it doesn't:
-copy the files into the corresponding directories BECAUSE it doesn't find the original files (which it read out itself previously). I honestly have no clue why that is.
Here the sourcecode:
package fotosorter;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Date;
public class Fotosorter {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws JpegProcessingException, IOException {
File startdir = new File(System.getProperty("user.dir"));
FileFilter jpg = new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getAbsoluteFile().toString().toLowerCase().endsWith(".jpg");
}
};
File dir = new File(startdir, "bitmaps"+File.separator+"java-temp");
if (!(dir.exists() && dir.isDirectory())) {
if (!dir.mkdir()) {
throw new IOException("kann das Verzeichnis nicht erzeugen ");
}
}
File[] files = new File(startdir, "" + File.separator + "bitmaps" + File.separator + "java-fotos").listFiles(jpg);
for (File file : files) {
Metadata metadata = JpegMetadataReader.readMetadata(file);
ExifIFD0Directory directory = metadata.getDirectory(ExifIFD0Directory.class);
String[] dates = directory.getDate(ExifIFD0Directory.TAG_DATETIME).toString().split(" ");
File year = new File(dir, dates[5]);
File month = new File(year, dates[1]);
File fname = new File(month, file.getName());
if (!(month.getParentFile().exists() && month.getParentFile().isDirectory())) {
if (!month.mkdirs()) {
throw new IOException("kann die Verzeichnisse nicht erzeugen");
}
}
copyFile(file, fname);
}
}
public static void copyFile(File from, File to) throws IOException {
Files.copy(from.toPath(), to.toPath());
}
}
And here the full exception it throws:
run:
Exception in thread "main" java.nio.file.NoSuchFileException: D:\Benutzerdaten\Paul\Documents\NetBeansProjects\Fotosorter\bitmaps\java-fotos\cimg2709.jpg -> D:\Benutzerdaten\Paul\Documents\NetBeansProjects\Fotosorter\bitmaps\java-temp\2008\Sep\cimg2709.jpg
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:205)
at sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:277)
at java.nio.file.Files.copy(Files.java:1225)
at fotosorter.Fotosorter.copyFile(Fotosorter.java:64)
at fotosorter.Fotosorter.main(Fotosorter.java:59)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
As you may have guessed it's not finished yet. Apart from solving my previously stated problem I still have to put it into methods.
Make sure that the input file exists.
But also make sure that the path of the destination folder does exist.

With a Collection of File, get a getPath() relate to specific folder

i'm using
org.apache.commons.io.FileUtils
for get all the filed PDF contained in a specified folder (and relative subfolders)
Here a simple code
import java.io.File;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
public class FileFilterTest
{
public static void main(String[] args)
{
File ROOT_DIR = new File("C:\\PDF_Folder");
Collection<File> PDF_FILES = FileUtils.listFiles(ROOT_DIR, new IOFileFilter() {
#Override
public boolean accept(File file)
{
return file.getName().endsWith(".pdf");
}
#Override
public boolean accept(File dir, String name)
{
return name.endsWith(".pdf");
}
}, TrueFileFilter.INSTANCE);
for(File pdf : PDF_FILES)
{
System.out.println(pdf.getPath());
}
}
}
the getPath() method returns the Absolute Path like this
C:\PDF_Folder\SomeFolder\AnotherFolder\A\20120430_TT006059__0000039.pdf
C:\PDF_Folder\Folder1\A\20120430_TT006060__000003A.pdf
C:\PDF_Folder\Folder1\Folder2\Folder3\B\20120430_TT006071__000003B.pdf
C:\PDF_Folder\Folder4\20120430_TT006125__000003C.pdf
Is there a way to get only the path related to the provided Root Folder?
SomeFolder\AnotherFolder\A\20120430_TT006059__0000039.pdf
Folder1\A\20120430_TT006060__000003A.pdf
Folder1\Folder2\Folder3\B\20120430_TT006071__000003B.pdf
Folder4\20120430_TT006125__000003C.pdf
EDIT: Here the solution created by code of jsn
for(File pdf : PDF_FILES)
{
URI rootURI = ROOT_DIR.toURI();
URI fileURI = pdf.toURI();
URI relativeURI = rootURI.relativize(fileURI);
String relativePath = relativeURI.getPath();
System.out.println(relativePath);
}
Something like this maybe:
String relPath = new File(".").toURI().relativize(pdf.toURI()).getPath();
System.out.println(relPath);
Tested, this works.
One way would be to simply 'subtract' the root path from the filename:
pdf.getPath().substring(ROOT_DIR.getPath().length() + 1)
You can you something like this as well:
for(File pdf : PDF_FILES)
{
System.out.println(pdf.getParentFile().getName()
+ System.getProperty("file.separator")
+ pdf.getName());
}

Categories

Resources