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;
}
}
}
}
Related
I created a Java program which basically moves all files within a specific "test" folder to a completely different and specific directory on the computer. How can I package the "test" folder, and both the java and class files into a single runnable JAR file?
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import javax.swing.JOptionPane;
public class Test
{
public static void main(String[] args) throws IOException
{
File sourceFolder = new File("test");
String dataFolder = System.getenv("APPDATA");
File destinationFolder = new File(dataFolder + "\\testing");
copyFolder(sourceFolder, destinationFolder);
}
private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
{
if (sourceFolder.isDirectory())
{
if (!destinationFolder.exists())
{
destinationFolder.mkdir();
}
String files[] = sourceFolder.list();
for (String file : files)
{
File srcFile = new File(sourceFolder, file);
File destFile = new File(destinationFolder, file);
copyFolder(srcFile, destFile);
}
JOptionPane.showMessageDialog(null,"File installed successfully","Title",1);
}
else
{
Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
I get this error I get when I move the test folder:
Exception in thread "main" java.nio.file.NoSuchFileException: test
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:85)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileCopy.copy(WindowsFileCopy.java:98)
at java.base/sun.nio.fs.WindowsFileSystemProvider.copy(WindowsFileSystemProvider.java:283)
at java.base/java.nio.file.Files.copy(Files.java:1298)
at Test.copyFolder(test.java:39)
at Test.main(test.java:16)
On the first run, I want to copy the given File to a new location with a new file name.
Every subsequent run should overwrite the same destination file created during first run.
During first run, the destination file does not exist. Only the directory exists.
I wrote the following program:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
However, this throws null pointer exception on the following line:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
What am I missing?
Directory someDir is directly under my project's root directory in eclipse.
Both source files myFile.txt and myFile_Another.txt exists directly under my project's root directory in eclipse.
I used this and it works as I am expecting:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
Using Java nio.
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.
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());
}
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);