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());
}
Related
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;
}
}
}
}
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.
Hi i want to recursively check if the files and subfolders of a certain directory contain a certain string so tried this
package com.tecsys.sm.test;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import com.tecsys.sm.util.WindowsDirectories;
public class ApacheListOfFiles {
public static void main(String[] args){
final String envName= "test_trunkcpsm";
WindowsDirectories wd = new WindowsDirectories();
File startPath = new File(wd.getStartMenuDir()+File.separator+"Programs");
Collection<File> listF = FileUtils.listFiles(startPath, new IOFileFilter() {
#Override
public boolean accept(File dir, String name) {
return false;
}
#Override
public boolean accept(File file) {
// TODO Auto-generated method stub
if(file.getName().contains(envName)){
System.out.println(file);
return true;
}else
return false;
}
},TrueFileFilter.INSTANCE);
System.out.println(listF.size());
Iterator<File> it = listF.iterator();
while(it.hasNext()){
System.out.println("Le fichier est : "+it.next());
}
}
}
The output of this is the following:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\TECSYS\iTopia Environments\test_trunkcpsm
0
So he finds the file i am searching for but still return an empty list, why is that ? And also while we are at it, when is the first accept called ? i have some difficulties understanding how this class works.
It works for me, may be the reason is false returned in the first accept().
You may also want to look at DelegateFileFilter to implement a single accept().
Or to use this single call for the job:
Collection listF = FileUtils.listFiles(
startPath, new WildcardFileFilter("*" + envName + "*"), TrueFileFilter.TRUE);
Servlet is very good looking and reading files that have English names like hello.txt. It does not want to read files that have a Russian name, such pushkin.txt. Is anyone able to help to solve this problem?
Here is the code:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class servlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public static List<String> getFileNames(File directory, String extension) {
List<String> list = new ArrayList<String>();
File[] total = directory.listFiles();
for (File file : total) {
if (file.getName().endsWith(extension)) {
list.add(file.getName());
}
if (file.isDirectory()) {
List<String> tempList = getFileNames(file, extension);
list.addAll(tempList);
}
}
return list;
}
#SuppressWarnings("resource")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html; charset=UTF-8");
String myName = request.getParameter("text");
List<String> files = getFileNames(new File("C:\\Users\\vany\\Desktop\\test"), "txt");
for (String string : files) {
if (myName.equals(string)) {
try {
File file = new File("C:\\Users\\vany\\Desktop\\test\\" + string);
FileReader reader = new FileReader(file);
int b;
PrintWriter writer = response.getWriter();
writer.print("<html>");
writer.print("<head>");
writer.print("<title>HelloWorld</title>");
writer.print("<body>");
writer.write("<div>");
while((b = reader.read()) != -1) {
writer.write((char) b);
}
writer.write("</div>");
writer.print("</body>");
writer.print("</html>");
}
finally {
if(reader != null) {
try{
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
The question is relevant, the problem is not solved
I thought that you have a problem whith the statements
for (String string : files) {
if (myName.equals(string)) {
I would compare in this way
for (File file: files) {
if (myName.equals(file.getName())) {
I hope that it help you.
Note: Thanks for the comments, you can try it.
Greetings
First of all I would use a debugger to check what's wrong with that code. It's quite difficult to find a bug without running the code. If you don't want to use a debugger print out all filenames found in the directory to ensure that some file names were found:
for (String string : files) {
System.out.println(string)
....
If files were found I would check whether I have rights to write to them. It might be that the application has not proper permissions to write in selected directory.
Are files "hello.txt" and pushkin.txt directly inside "C:\Users\vany\Desktop\test\" folder? Or is pushkin.txt file in another folder from "C:\Users\vany\Desktop\test\"?
Can you show us how you invoke the servlet?
If you have pushkin.txt in another folder and you invoke the servlet with something like "folder\pushkin.txt" it will not work because getFileNames() returns file names (without folder) and "myName.equals(string)" fails as "folder\pushkin.txt" is not equal to "pushkin.txt"
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);