Get the list of all files under the folder resources - java

My unit test project structure looks like this:
.
└── src
└── test
├── java
│ └── foo
│ └── MyTest.java
└── resources
├── file1
|-- ...
└── fileN
In MyTest.java, I would like to get a list of all files under src/test/resources/ :
File[] files = GET_ALL_RESOURCE_FILES();
how to do it in Java?

Try this as your code:
File Selected_Folder = new File(System.getProperty("user.dir")+"/src/test/resources/");
File[] list_of_files = Selected_Folder.listFiles();
For viewing the files under that particular directory from where you have selected the files... you can do this...
for(int i=0; i<list_of_files.length; i++)
{
System.out.println(" File Number "+(i+1)+" = "+list_of_files[i]);
}

My Approach--
File[] GET_ALL_RESOURCE_FILES(final File file)
{
java.util.List<File> ls = new ArrayList<File>();
for (final File fileIter : file.listFiles()) {
if (fileIter.isDirectory())
loadAll(fileIter);
else
ls.add(fileIter);
}
return ls.toArray();}
Now call this function--
File[] files = GET_ALL_RESOURCE_FILES('src/test/resources/');

Try this File folder = new File(System.getProperty("user.dir")+"/src/test/resources/");
File[] files = folder.listFiles();
System.getProperty("user.dir") will return path of your current working directory. In maven projects it returns path of your maven project folder which is parent folder of src folder.

Related

Unable to zip symlinks that link to directories Zip4j

With Zip4j, I've been able to successfully zip symlinks that link to regular files correctly. However, symlinks that link to directories aren't working for me. Keep in mind that I'm trying to mirror the following shell command from Info-ZIP: zip -yr someDirectory.
Toy example:
I created one directory with a symlink to it and a regular file with a symlink to it like so:
$ mkdir tmp
$ cd tmp
$ mkdir a; ln -s a b; touch c; ln -s c d
$ cd ..
$ tree tmp
tmp
├── a
├── b -> a
├── c
└── d -> c
Ideally what would happen is the following:
$ zip -yr tmp.zip tmp
$ unzip tmp.zip -d newtmp
Archive: tmp.zip
creating: newtmp/tmp/
creating: newtmp/tmp/a/
extracting: newtmp/tmp/c
linking: newtmp/tmp/d -> c
linking: newtmp/tmp/b -> a
finishing deferred symbolic links:
newtmp/tmp/d -> c
newtmp/tmp/b -> a
$ tree newtmp
newtmp
└── tmp
├── a
├── b -> a
├── c
└── d -> c
I then attempted to use Zip4j to zip these files.
For symlinks, I call setSymbolicLinkAction with INCLUDE_LINK_ONLY and manually set CompressionLevel.NO_COMPRESSION and CompressionMethod.STORE. I also set the filename for directories such that they are appended with a /.
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class ZipTest {
public static void main(String[] args) throws IOException {
try (ZipFile zipFile = new ZipFile("test.zip");
Stream<Path> paths = Files.walk(Paths.get("tmp"))) {
paths.forEach(path -> {
ZipParameters zp = new ZipParameters();
if ((!Files.isSymbolicLink(path)) && Files.isDirectory(path)) {
zp.setFileNameInZip(path + "/");
} else {
zp.setFileNameInZip(path.toString());
}
if (Files.isSymbolicLink(path)) {
zp.setSymbolicLinkAction(ZipParameters.SymbolicLinkAction.INCLUDE_LINK_ONLY);
zp.setCompressionLevel(CompressionLevel.NO_COMPRESSION);
zp.setCompressionMethod(CompressionMethod.STORE);
}
try {
zipFile.addFile(path.toFile(), zp);
} catch (ZipException e) {
throw new RuntimeException(e);
}
});
}
}
}
Unzipping output:
$ unzip test.zip -d test
Archive: test.zip
creating: test/tmp/
creating: test/tmp/a/
extracting: test/tmp/c
linking: test/tmp/d -> c
extracting: test/tmp/b
finishing deferred symbolic links:
test/tmp/d -> c
That didn't work. The symlink b to directory a did not stay a symlink. I've also tried:
allowing symlinks identified as directories to have / in their file name.
zip parameters without setting compression
calling the addFolder API on just the input directory
and nothing has worked so far.
This is now a known bug in Zip4j. See https://github.com/srikanth-lingala/zip4j/issues/486.

How to read files from the sub folder of resource folder

How to read files from the sub folder of resource folder.
I have some json file in resources folder like :
src
main
resources
jsonData
d1.json
d2.json
d3.json
Now I want to read this in my class which is
src
main
java
com
myFile
classes
here is what I am trying but getting failed.
File folder = new File("./src/main/java/resources/jsonData/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
// my operation of Data.
}
}
Not working then I am trying :
Resource resource = new ClassPathResource("classpath:jsonData/data1.json");
File folder = new File(resource.getURI());
File[] listOfFiles = folder.listFiles();
both of things are not working.
You should be able to achieve this using getClass.GetResource()
File[] fileList = (new File(getClass().getResource("/exampleFolder").toURI())).listFiles();

How to list directory items from a directory java [duplicate]

This question already has answers here:
Recursively list files in Java
(30 answers)
Closed 1 year ago.
I am building a program where the input is a directory path and the output should show all files in this path, including the files from a directory, which are in the given path. For example: Input: C: Output: C:/Directory1 and C:/Directory1/file1.pdf.
static string Directory = sc.next();
static File folder = new File(Directory);
static File[]listofFiles = folder.listFiles();
public static void ListOfFilesInADirectory (final File folder) {
for (int i = 0; i < listofFiles.length; i++) {
if (listofFiles[i].isFile()) {
System.out.println("File " + listofFiles[i].getName());
} else if (listofFiles[i].isDirectory()) {
System.out.println("Directory " + listofFiles[i].getName());
}
}
}
The code above is the code for the input of the directory and the output of all the files in this directory, but not them in a folder, of this directory. How can I show the files in folders of the director too?
It sounds like you want something like this...
\---folder
| file1.txt
| file2.txt
|
\---subfolder
file3.txt
file4.txt
To print...
folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt
If that assumption is right, one solution is to try using java.nio.file.Files.walk(Path).
Files.walk(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);//print out the files in all directories from root
Files.walk(path) can return those subfolder files by walking the file tree rooted at the start file given.

Not able to access file in eclipse gives : FileNotFoundException

In eclipse i am trying to give path of one configuration.json file but it is not taking it .
System.getProperty("user.dir")
gives C:\Users\cmalik\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse
and
try {
File f = new File("."); // current directory
File[] files = f.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
gives
file:C:\Users\cm\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse\Eclipse Jee Neon.lnk
file:C:\Users\cm\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse\hs_err_pid10180.log
file:C:\Users\cm\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Eclipse\hs_err_pid9728.log
And my project structure is
ProjectName
---src
---- com.abc.def.ghi.jkl.WebServices
------ myService.java
---configuration.json
I tried code for accessing file is :
FileReader file = new FileReader("configuration.json");
or
FileReader file = new FileReader("projectName\\configuration.json");
It is not able to access as output for System.getProperty("user.dir") is eclipse folder not my current projectName folder.
How can i get my files please let me know.
You can use either of the below two:
String location=System.getProperty("user.dir");
or
String location= new java.io.File(".").getCanonicalPath();
And then try to access the file using:
FileReader file = new FileReader(location+"\\configuration.json");
Hope it helps.

FileInputStream can not open a `relative path` file correctly with specific `user.dir` value

The project use maven to build and its file structure as follows.
fnlp
├── fnlp-app
├── fnlp-core
├── models
│   └── seg.m
└── tmp
└── lucene
Now, I switched working directory to sub-module fnlp-app and set VM OPTIONS
with -Duser.dir=$MODULE_DIR$.
Directory dir = FSDirectory.open(new File("../tmp/lucene"));
When used FSDirectory.open, it can get an expected result.
FileInputStream fileInputStream = new FileInputStream(new File("../models/seg.m"));
However, executed above code, it got java.io.FileNotFoundException: ../models/seg.m (No such file or directory)
Simple test code snippet and logs.(Thanks #jon-skeet 's suggestion.)
System.out.println(System.getProperty("user.dir"));
// Output: /home/xohozu/workbench/git/github/fnlp/fnlp-app
System.out.println(new File("./models/seg.m").getCanonicalPath());
// Output: /home/xohozu/workbench/git/github/fnlp/fnlp-app/models/seg.m
FileInputStream inSteam1 = new FileInputStream(new File("./models/seg.m"));
// Passed
FileInputStream inSteam11 = new FileInputStream(new File("/home/xohozu/workbench/git/github/fnlp/fnlp-app/models/seg.m"));
// Exception in thread "main" java.io.FileNotFoundException: /home/xohozu/workbench/git/github/fnlp/fnlp-app/models/seg.m (No such file or directory)
System.out.println(new File("../models/seg.m").getCanonicalPath());
// Output: /home/xohozu/workbench/git/github/fnlp/models/seg.m
FileInputStream inSteam2 = new FileInputStream(new File("../models/seg.m"));
// Exception in thread "main" java.io.FileNotFoundException: ../models/seg.m (No such file or directory)
FileInputStream inSteam22 = new FileInputStream(new File("/home/xohozu/workbench/git/github/fnlp/models/seg.m"));
// Passed

Categories