I have read many other questions and resources regarding this issue and am still getting nowhere. I asked a question about this the other day and was referred to the other questions again. Maybe I am just not getting it but I have been trying to getResourceAsStream for my java project for 2 days so I can get the jar to work to no avail.
I have two places in my project causing issues. My buffered image class:
public static BufferedImage loadImage(String fileName) {
try {
File file = new File(fileName);
//System.out.println("Is the file there for " + fileName + " : " + file.exists());
BufferedImage sub = ImageIO.read(file);
return toCompatibleImage(sub);
}
catch (IOException e) {
System.out.println("Image load failed: " +fileName);
// e.printStackTrace();
return null;
}
}
My GifHandler class:
public enum GifHandler {
Mouse("Resources/Images/cursor/", ".gif", 45, 45),
Coaster("Resources/Images/animatedCoaster/", ".gif", Carnies.PWIDTH, Carnies.PHEIGHT/2),
Fire("Resources/Images/fire/", ".gif", 100, 100);
public BufferedImage[] sequence;
int playing = 0;
GifHandler(String dir_name, String type, int width, int height) {
int numImgs = new File(dir_name).list().length;
if (sequence == null) {
sequence = new BufferedImage[numImgs];
for (int i = 0; i < numImgs; i++) {
sequence[i] = ImageLoader.loadScaledImage(dir_name + i + type, width, height, false);
}
}
}
}
I have added the resources folder to my build path libraries. My project file structure is like this:
"Project/src/defaultpackage/classfiles"
"Project/resources/Images/imagefiles"
I want to reference the imagefiles from the classfiles, obviously.
I have tried changing to getResourceAsStream, but always get null on the path.
For example, a change to the imageLoader class as shown, returns null:
String path = ImageLoader.class.getResourceAsStream(fileName).toString();
Where fileName is passed in as "resource/Images/alphabet.png" for example.
I've tried every combination of adding and removing /, only referencing the /alphabet.png without leading folders etc. I am at the end of my rope. Please help out. If I haven't linked enough code for this to make sense, the repo for it is at github.com/madamsmall/carnies
My project file structure is like this: "Project/src/defaultpackage/classfiles" "Project/resources/Images/imagefiles"
When you use getClass().getResourceAsStream(), the program will start it's search from the location of the calling class. So by passing "resource/Images/alphabet.png", you're saying that resources is in classfiles, which it isn't. To fix it, you need to allow the search to be traversed back. You can do that by adding a / to the path. So getClass().getResourceAsStream("/resource/Images/alphabet.png")
Another option is to use the the class loader, which will search from the the root. In that case, you don't need the extra / and your current path would be correct. getClass().getClassLoader().getResourceAsStream("resource/Images/alphabet.png");
Note: getClass() and ImageLoader.class are interchangeable in most cases, in case you're wondering why I used getClass()
UPDATE
Use this example as a test
import java.awt.Image;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageLoader {
public static void main(String[] args) throws IOException {
InputStream is = ImageLoader.class.getResourceAsStream("/resource/images/alphabet.png");
Image image = ImageIO.read(is);
JLabel label = new JLabel(new ImageIcon(image));
JOptionPane.showMessageDialog(null, label);
}
}
UPDATE 2
I just noticed that resource is not in your src which it should be, so when it's built, it gets built into the class path.
UPDATE 3
If you want to get a list of all the file names, you can use this method. Then you can do whatever you want with those file names.
private String[] getFileNames() throws URISyntaxException {
URL url = getClass().getResource("/resources/images/");
File file = new File(url.toURI());
String[] fileNames = file.list();
for (String s : fileNames) {
System.out.println(s);
}
return fileNames;
}
Related
I am trying to scan the "loremIpsum.txt" file to a String using the split method of the class String to store each word in a different position of an array, and last use a HashSet to find if there is any word repetition in the text.
But Eclipse doesn't recognize the file even though it is in the same package. I was wondering if there is something wrong with my code?
package Lab5;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Lorem {
public static void main(String[] args) {
String[] loremIpsum = null;
try {
loremIpsum = new Scanner(new File("loremIpsum.txt")).next().split(" ");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(loremIpsum.length);
HashSet h = new HashSet();
for(int i=0;i<loremIpsum.length;i++) {
String word=loremIpsum[i];
System.out.println(word);
if(h.contains(word)) {
System.out.println("we found a duplicate");
} else {
h.add(word);
}
}
}
}
Error message and proof "lorem.txt" is in the same package:
The file will be looked for in the project directory (where bin and src folders are located). Move the file there.
You need to pass the parameter as a path.
try this
String path = new File("").getAbsolutePath();
path.concat("/loremIpsum.txt");
loremIpsum = new Scanner(new File(path)).next().split(" ");
basically youre just finding the current path and appending the file name youre wanting to read from.
Like the others said though, you can move it to your working directory as well.
Cheers!
When you call the File constructor with a relative path, it's relative to the working directory.
That usually won't be the same directory as the code calling the constructor. But that's okay, because if your file can be specified when you run the application, you don't want to presume that anyway.
You can specify the working directory in the Eclipse run configuration, on the Arguments tab.
You can see how a relative path has been resolved using the File method getAbsolutePath().
try {
File myFile = new File("loremIpsum.txt");
System.out.println("Absolute path = " + myFile.getAbsolutePath() );
loremIpsum = new Scanner(myFile).next().split(" ");
...
I want to create shortcuts inwindows with code, I use the library here:
http://alumnus.caltech.edu/~jimmc/jshortcut/jshortcut/README.html
also the corresponding codes:
import net.jimmc.jshortcut.JShellLink;
public class remove {
public static void main(String[] args) throws Exception{
String path = new String ("/home/test.csv");
readAndDelete(path, true, StandardCharsets.UTF_8);
}
private static void readAndDelete(String path, boolean ignoreHeader,Charset encoding) throws IOException {
File file = new File(path);
CSVParser parser = CSVParser.parse(file, encoding,CSVFormat.DEFAULT.withHeader());
List<CSVRecord> records = parser.getRecords();
List<String> docRecord = new ArrayList<String>();
List<String> shortpath = new ArrayList<String>();
for (CSVRecord doctype : records){
docRecord.add(doctype.get(0).toString());
shortpath.add(doctype.get(1).toString());
}
int recordlength = docRecord.size();
for(String eachdocRecord:docRecord){
try {
Path pathtemp=Paths.get(eachdocRecord);
Files.delete(pathtemp);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
}
for(int i=0; i<recordlength; i++){
JShellLink link = new JShellLink();
String pointpath=shortpath.get(i);
String originalpath = docRecord.get(i);
String[] parts = pointpath.split("\\\\");
int partssize= parts.length;
String name=parts[partssize-1];
String[] originalparts = originalpath.split("\\\\");
int originalsize = originalparts.length;
int lastlength = originalparts[originalsize-1].length();
String foldername = originalpath.substring(0,originalpath.length()-lastlength);
link.setFolder(foldername);
link.setName(name);
link.setPath(pointpath);
link.save();
}
}
}
I run it in windows command prompt, but always exception:
Exception in thread "main" java.lang.NoClassDefFoundError:net/jimmc/jshortcut/JShellLink
I compiled the .class successfully ...
Anyone could save nme ... thanks a lot
Regardless of anything else that might be wrong (I did not read the entire code) the exception is quite clear - JShellLink is not on your classpath. How to do it best depends on your use case - README suggests editing Manifest file when you build to .jar, it should also be possible to use Maven to take care of that, and any IDE should have been able to take care of classpaths for you. As far as I can tell however your use case looks something like
javac remove.java
java remove
(By the way, class names and class file names should start with upper case, that's the standard)
In that case the simplest way to do that would be to use:
java -cp .;jshortcut.jar remove
We add current directory (due to JShortcut wanting to have it's dll on classpath, just to be sure) as well as the jar containing classes you use to the classpath. If you're on Unix system use : instead of ;.
I am trying to extract list of zip files from folder and then re-zipping them with password. The problem is while re-zipping, the iteration/loop is not stopping. Also, re-zipped files should be a separate zip file each rather than merging all contents to one zip.
Here's what I have tried:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
public class AddFilesWithAESEncryption2 {
public AddFilesWithAESEncryption2() {
try {
//Extract Zip files as folders
try {
String ZipSourcePath = "E:/EZipTest/";
String ExtractTo = "D:/DZipTest/";
String files1;
File folder1 = new File(ZipSourcePath);
File[] listOfFiles1 = folder1.listFiles();
for (int i = 0; i < listOfFiles1.length; i++) {
if (listOfFiles1[i].isFile()) {
files1 = listOfFiles1[i].getName();
String ZipFiles = "E:/EZipTest/" + files1;
try {
ZipFile zipFile = new ZipFile(ZipFiles);
List fileHeaderList = zipFile.getFileHeaders();
zipFile.extractAll(ExtractTo);
} catch (ZipException e) {
e.printStackTrace();
}
}
}
//Get list of folders
String DirectoryNames;
String ExtractedDirectories1 = "D:/DZipTest/";
File folder2 = new File(ExtractedDirectories1);
File[] listOfFiles2 = folder2.listFiles();
for (int i = 0; i < listOfFiles2.length; i++) {
if (listOfFiles2[i].isDirectory()) {
DirectoryNames = listOfFiles2[i].getName();
String ListOfDirectories = "D:/DZipTest/" + DirectoryNames;
//Get list of files
String ExtractedDirectories = ListOfDirectories;
File folder3 = new File(ExtractedDirectories);
File[] listOfFiles3 = folder3.listFiles();
for (int j = 0; j < listOfFiles3.length; j++) {
File file = listOfFiles3[j];
if (file.isFile()) {
String FileNames = file.getName();
System.out.println(ListOfDirectories + FileNames);
//Compress and zip the files
ZipFile zipFile = new ZipFile("D:/" + listOfFiles2[i].getName() + ".zip");
ArrayList filesToAdd = new ArrayList();
filesToAdd.add(new File(ListOfDirectories + FileNames));
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword("test");
zipFile.addFiles(filesToAdd, parameters);
}
}
}
}
} catch (ZipException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new AddFilesWithAESEncryption2();
}
}
Refactoring
Refactoring your code will help you understand what it does. It will reveal the problem and immediately identify a fix. Here's how it goes. Note that this is not a complete tutorial, but I hope you get the point.
First, extract a nice method that does the unzipping. Mark everything inside the first for loop, then right click and choose Refactor / Extract Method.... Name it unzipFile. Note that you now have a nice small, potentially reusable and potentially testable (JUnit) method.
Next, mark everything from ZipParameters parameters to parameters.setPassword("test"); Right click, Refactor / Extract Method.... Name it getEncryptionParameters. Note how 7 lines of code have been removed from the long method and readability is improved.
Right click on parameters and choose Refactor / Inline .... Note how the temporary variable disappears.
See the bug
If you have followed closely, there is a piece of code like this:
//Compress and zip the files
ZipFile zipFile = new ZipFile("D:/" + listOfFiles2[i].getName() + ".zip");
ArrayList filesToAdd = new ArrayList();
filesToAdd.add(new File(ListOfDirectories + FileNames));
zipFile.addFiles(filesToAdd, getEncryptionParameters());
See what it does? It creates a new ZIP file, adds only one file to filesToAdd and that's it. But why? It says FileNames. How can that be one file only?
Looking at
String FileNames = file.getName();
that's really just one file, so the variable name is wrong.
Right click FileNames and choose Refactor/Rename.... Enter fileName. Note how the variable name in your program matches to what it really is. It heavily improves readability of the code.
Simplify
Now that you know you're adding only one file, use addFile() instead of addFiles(). You're getting rid of the ArrayList:
//Compress and zip the files
ZipFile zipFile = new ZipFile("D:/" + listOfFiles2[i].getName() + ".zip");
File fileToAdd = new File(ListOfDirectories + fileName);
zipFile.addFile(fileToAdd, getEncryptionParameters());
Fix the bug
As spotted before, a new ZipFile(...) is created inside the loop and only one file is added to it. Move that line out of the loop pressing Alt+Up.
Continue refactoring
A part of the problem is already fixed (I haven't tried, actually), but your code is still not error-free. Let's go on:
Mark everything from File[] listOfFiles3 to the end of the for loop that follows. Right click, Refactor/Extract Method..., name it rezip. Your big method becomes smaller again.
Right click on ExtractedDirectories, Refactor / Inline .... You just got rid of a unnecessary temporary variable.
See something? Your code should look like this:
//Get list of files
File folder3 = new File(ListOfDirectories);
rezip(listOfFiles2, i, ListOfDirectories, folder3);
Note how folder3 and ListOfDirectories is essentially the same. Let's get rid of it. Move the line File folder3 = new File(ListOfDirectories); into the method, just behind private void rezip(...){ and remove the parameter File folder3 from both, the method call and the method declaration of rezip().
The loop using rezip() now looks like this:
for (int i = 0; i < listOfFiles2.length; i++) {
if (listOfFiles2[i].isDirectory()) {
DirectoryNames = listOfFiles2[i].getName();
String ListOfDirectories = "D:/DZipTest/" + DirectoryNames;
rezip(listOfFiles2, i, ListOfDirectories);
}
}
You might spot that DirectoryNames is actually just one, not many. Right click, Refactor/Rename.... Enter subDirectory.
Right click subDirectory, Refactor / Inline .... Read the error message. Right click References / Workspace. Check the results and find out that this variable is only used within the for loop. Delete the declaration outside and declare it at its first use. Now do the Refactor / Inline ... operation.
Your code looks like this:
for (int i = 0; i < listOfFiles2.length; i++) {
if (listOfFiles2[i].isDirectory()) {
String ListOfDirectories = "D:/DZipTest/" + listOfFiles2[i].getName();
rezip(listOfFiles2, i, ListOfDirectories);
}
}
Again, there's a variable name indicating a list or an Array, but that's not true. Refactor / Rename..., name it directoryToZip.
Inline the following variables in this order: ExtractedDirectories1, folder2, ZipSourcePath, folder1.
Rename in this order listOfFiles1 to zipFiles and listOfFiles2 to extractedDirectories.
Remove files1 since it is never used.
The final bug
The method is now short and readable enough to understand it completely. Does the following make sense?
String ExtractTo = "D:/DZipTest/";
File[] zipFiles = new File("E:/EZipTest/").listFiles();
for (int i = 0; i < zipFiles.length; i++) {
unzipFile(ExtractTo, zipFiles, i);
}
File[] extractedDirectories = new File("D:/DZipTest/").listFiles();
for (int i = 0; i < extractedDirectories.length; i++) {
if (extractedDirectories[i].isDirectory()) {
String directoryToZip = "D:/DZipTest/" + extractedDirectories[i].getName();
rezip(extractedDirectories, i, directoryToZip);
}
}
No it doesn't.
You don't want to extract all archives first but one by one
You don't want to zip subdirectories, you want to zip everything in the ExtractTo directory
Fixing the final bug
The signature of unzipFile() does not look right. If it unzips one file only as the name suggests, why does it get access to all files then?
Replace unzipFile(ExtractTo, zipFiles, i); by unzipFile(ExtractTo, zipFiles[i]);. This breaks the code. Eclipse will mark it red. Fix it by changing the parameters from
private void unzipFile(String ExtractTo, File[] listOfFiles1, int i)
to
private void unzipFile(String ExtractTo, File listOfFiles1)
Inside unzip, replace listOfFiles1[i] by listOfFiles1. Then Refactor/Rename... it to sourceZipFile.
Similar for the rezip method: it should get the directory to zip and the target file name only. Therefore change
rezip(extractedDirectories, i, directoryToZip);
to
rezip(extractedDirectories[i], directoryToZip);
Then adapt the method itself from
private void rezip(File[] listOfFiles2, int i, String ListOfDirectories) throws ZipException
to
private void rezip(File listOfFiles2, String ListOfDirectories) throws ZipException
then change listOfFiles2[i] to listOfFiles2. Rename it to targetFile.
Now you have a nice unzipFile() method and a rezip() method. Let's combine it in a cool way:
String ExtractTo = "D:/DZipTest/";
File[] zipFiles = new File("E:/EZipTest/").listFiles();
for (int i = 0; i < zipFiles.length; i++) {
unzipFile(ExtractTo, zipFiles[i]);
rezip(zipFiles[i], ExtractTo);
// TODO: delete extracted files here
}
Awesome, ain't it?
Notes
Maybe you've seen how much effort it is to understand your code and provide a fix. Actually, too much effort for Stack Overflow. Next time you ask a question, please try to provide code that is at minumum as readable as your code now.
The code is still not as clean as it should be. Spend some more time on it. When you think it's superb, post it on https://codereview.stackexchange.com/ to get even more instructions.
I wrote a file writing script that lets you write in a file you are looking for in the console, then when you press enter it tries to find the file to see if it exists. My program works, but I don't like that I need the full pathname, every single time. I want a user to just be able to write, say, file_name.txt and the program searches a single directory for it.
Currently, I must use the full pathname every single time. This is not all of my code, but you can see that my file names have a hard coded String pathname. But what if someone else wants to run the program on their own computer? I tried looking for answers to this, but Java is always very difficult for me. If you know a way to make my code generic enough so my Scanner object can take just the file name, that would be so helpful. Thanks, let me know if anything is unclear. I have a Mac, but it should be able to work on any OS.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;
public class FileHandler {
public static boolean fileCheck = true;
public static File logFile;
public static PrintWriter logPrinter;
public static PrintWriter handMadeFile;
public static LocalDate date = LocalDate.now();
public static File fileFromScanner;
public static File directory = new File("/Users/mizu/homework");
public static String fileName;
public static File file;
public static String created = "Log has been created.";
public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
public static String mainFileName = "/Users/mizu/homework/main_file.txt";
public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
public static String fileMessage = "I just wrote my own file contents.";
public static void main(String[] args) {
if (!directory.exists())
{
// create new directory called homework
directory.mkdir();
}
// gets file request from user
System.out.print("Enter file to find: ");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
// initialize the main_file
fileFromScanner = new File(mainFileName);
// if main_file exists or not, print message to my_log
if (!fileFromScanner.exists())
{
// create my_log file (logFile), to keep track of events
writeToLog(created);
writeToLog("File path you entered: "
+ fileName + " does not exist.");
System.out.println(fileName + " - does not exist.");
// create file since it doesn't exist
File mainFile = new File(mainFileName);
try {
PrintWriter pwMain = new PrintWriter(new BufferedWriter
(new FileWriter(mainFile)));
writeToLog("Created " + mainFileName);
pwMain.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
writeToLog(fileName + " already exists.");
System.out.println(fileName + " - already exists.");
}
// use writeToFile method to write file, create new file name
FileHandler testFile = new FileHandler(fileFromMethod);
testFile.writeToFile(testFile, fileMessage);
} // end Main
All of the other methods are below here, but not shown to keep it short.
As stated in the comments, there are several tools already available to search files in a directory. However, to answer your question, I wrote a simple program that should do what you are looking for:
public static void main(String[] args) {
// Get the absolute path from where your application has initialized
File workingDirectory = new File(System.getProperty("user.dir"));
// Get user input
String query = new Scanner(System.in).next();
// Perform a search in the working directory
List<File> files = search(workingDirectory, query);
// Check if there are no matching files
if (files.isEmpty()) {
System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
+ query + "'");
return;
}
// print all the files that matched the query
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}
public static List<File> search(File file, String query) {
List<File> fileList = new ArrayList<File>();
// Get all the files in this directory
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
// use recursion to search in all directories for the file
fileList.addAll(search(f, query));
} else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
// if the filename matches the query, add it to the list
fileList.add(f);
}
}
}
return fileList;
}
1- You can make users set an environment variable to your path and use the path name in your code.
2- You can check the operating system, and put your files in a well-known folder. (C: for windows, /home for Ubuntu, /WhateverMacFolder for mac and if it is some other os ask user to enter the path.
3- You can create a folder in default path of your program and use it.
Hi right now I have the following method I am using to read one file at a time in a the same directory as the class that has this method:
private byte[][] getDoubleByteArrayOfFile(String fileName, Region region)
throws IOException
{
BufferedImage image = ImageIO.read(getClass().getResource(fileName));
byte[][] alphaInputData =
new byte[region.getInputXAxisLength()][region.getInputYAxisLength()];
for (int x = 0; x < alphaInputData.length; x++)
{
for (int y = 0; y < alphaInputData[x].length; y++)
{
int color = image.getRGB(x, y);
alphaInputData[x][y] = (byte)(color >> 23);
}
}
return alphaInputData;
}
I was wondering how I can make it so that instead of having "fileName" as a argument I can but a directory name as a argument and then iterate through all of the files within that directory and perform the same operation on it. Thanks!
If you are using Java 7, then you need to take a look at NIO.2.
Specifically, take a look at the Listing a Directory's Contents section.
Path dir = Paths.get("/directory/path");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
getDoubleByteArrayOfFile(file.getFileName(), someRegion);
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by newDirectoryStream.
System.err.println(x);
}
Here is a quick example that may help:
private ArrayList<byte[][]> getDoubleByteArrayOfDirectory(String dirName,
Region region) throws IOException {
ArrayList<byte[][]> results = new ArrayList<byte[][]>();
File directory = new File(dirName);
if (!directory.isDirectory()) return null //or handle however you wish
for (File file : directory.listFiles()) {
results.add(getDoubleByteArrayOfFile(file.getName()), region);
}
return results;
}
Not exactly what you asked for since it's wrapping your old method rather than re-writing it, but I find it a bit cleaner this way, and leaves you with the option of still processing a single file. Be sure to tweak the return type and how to handle the region based on your actual requirements (hard to tell from the question).
It is rather simple, using the File#listFiles() which returns a list of files in the specified File, which must be a directory. To make sure that the File is a directory, simply use File#isDirectory(). The problem occurs where you decide how to return the byte buffer. Since the method returns a 2d buffer, it is necessary to use a 3d byte buffer array, or in this case a List seems to me like the best choice since an unknown number of files will exist in the directory in question.
private List getDoubleByteArrayOfDirectory(String directory, Region region) throws IOException {
File directoryFile = new File(directory);
if(!directoryFile.isDirectory()) {
throw new IllegalArgumentException("path must be a directory");
}
List results = new ArrayList();
for(File temp : directoryFile.listFiles()) {
if(temp.isDirectory()) {
results.addAll(getDoubleByteArrayOfDirectory(temp.getPath(), region));
}else {
results.add(getDoubleByteArrayOfFile(temp.getPath(), region));
}
}
return results;
}
You can, see the list and listFiles documentation for how to do this.
We can use recursion to process a directory with subdirectories also. Here I am deleting file one by one, you can call any other function to process it.
public static void recursiveProcess(File file) {
//to end the recursive loop
if (!file.exists())
return;
//if directory, go inside and call recursively
if (file.isDirectory()) {
for (File f : file.listFiles()) {
//call recursively
recursiveProcess(f);
}
}
//call processing function, for example here I am deleting
file.delete();
System.out.println("Deleted (Processed) file/folder: "+file.getAbsolutePath());
}