Java - How to read all files in the same directory - java

I need to read all files in the same directory and store those files in a list. All files end in .txt and there are no subdirectory.
List<String> recipe = new ArrayList<>();
try {
recipe = Files.readAllLines(Paths.get("gyro.txt"));
}

You can get an array of files (according to the specified folder), after that you can iterate by each file in the folder and add all the characters from the file.
Can you please try to use the following code:
public static List<String> readFromAllFilesInDirectory(final String folderName) {
File folder = new File(folderName);
List<String> recipe = new ArrayList<>();
for (final File file : Objects.requireNonNull(folder.listFiles())) {
if (!file.isDirectory()) {
try {
recipe.addAll(Files.readAllLines(Paths.get(file.getPath())));
} catch (Exception e) {
}
}
}
return recipe;
}
public static void main(String[] args) {
File folder = new File("G:\\B\\1.txt");
System.out.println(readFromAllFilesInDirectory(folder.getParent()));
}

Try use the FileNameFilter class: Java FileNameFilter interface has method boolean accept(File dir, String name) that should be implemented and every file is tested for this method to be included in the file list.
File directory = new File("D://");
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
for (File file : files) {
System.out.println(file.getAbsolutePath());
}

Related

How to delete files with a certain extension from a folder in Andorid

I m a newbie in Android. I generate a record audio file, generate a text file, zip the two files and encrypt them.
I want to delete the following extensions .txt, .mp4 and .zip. I only want my encrypted file to remain in my directory containing .txt and .mp4
I did research and come across the following source and try to modified it.
private static final String DEFAULT_STORAGE_DIRECTORY = "Recorder";
private static final String FILE_RECORD_EXT = ".mp4";
private static final String FILE_INI_EXT = ".txt";
private static final String FILE_ZIP_EXT = ".zip";
public static void main(String args[]) {
new FileChecker().deleteFile(DEFAULT_STORAGE_DIRECTORY,FILE_RECORD_EXT,FILE_TXT_EXT);
}
public void deleteFile(String folder, String ext, String fileTxtExt){
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
String[] list = dir.list(filter);
if (list.length == 0) return;
//Files
File fileDelete;
for (String file : list){
String temp = new StringBuffer(DEFAULT_STORAGE_DIRECTORY)
.append(File.separator)
.append(file).toString();
fileDelete = new File(temp);
boolean isdeleted = fileDelete.delete();
System.out.println("file : " + temp + " is deleted : " + isdeleted);
}
}
//inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
Your help will be appreciated.
void deleteFiles(String folder, String ext)
{
File dir = new File(folder);
if (!dir.exists())
return;
File[] files = dir.listFiles(new GenericExtFilter(ext));
for (File file : files)
{
if (!file.isDirectory())
{
boolean result = file.delete();
Log.d("TAG", "Deleted:" + result);
}
}
}
Here is my working code for this. Please follow the comments inline to understand it's flow & function.
//dirpath= Directory path which needs to be checked
//ext= Extension of files to deleted like .csv, .txt
public void deleteFiles(String dirPath, String ext) {
File dir = new File(dirPath);
//Checking the directory exists
if (!dir.exists())
return;
//Getting the list of all the files in the specific direcotry
File fList[] = dir.listFiles();
for (File f : fList) {
//checking the extension of the file with endsWith method.
if (f.getName().endsWith(ext)) {
f.delete();
}
}
}

Unable to Access files in Directory

I have a directory structure as follows:
DB_SET
-D1
- DB_1.txt
-D2
- DB_2.txt
-D3
- DB_3.txt
-D4
- DB_4.txt
-D5
- DB_5.txt
I want to store all DB_1.txt, DB_2.txt, DB_3.txt, DB_4.txt, DB_5.txt in an ArrayList. How can I do this?
My Partial code:
File folder = new File("./WebContent/datasets/DB_Set/");
File[] listOfFiles = folder.listFiles();
System.out.println("listofFiles: "+listOfFiles);
ArrayList<File> sub_dir = new ArrayList<File>();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
}
else if (listOfFiles[i].isDirectory()) {
sub_dir.add(listOfFiles[i]);
}
}
You need to go into 2 levels deep.
File folder = new File("./WebContent/datasets/DB_Set/");
File[] listOfSubDirectories = folder.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isDirectory();
}
});
ArrayList<File> filesList = new ArrayList<File>();
for (File dir : listOfSubDirectories) {
File[] files = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
for (File f : files) {
filesList.add(f);
}
}
Create a FileFilter that implements accept, something like
boolean accept(File pathname) {
returns pathname != null && pathname.isFile();
}
and then call listFiles() with the filter
File[] files = folder.listFiles(my_file_filter);
and files should contain only the files. If you need to make sure the file names all end with .txt (because there could be other files in the directories) then add a string check of the file name.
Another approach to this would be to accumulate the files recursively:
private static List<String> addFiles (File dir) {
List<String> result = new ArrayList<String>();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
restult.addAll(addFiles(f));
} else if (f.isFile()) {
result.add(f.getName());
} else { // Just in case it's not a file or directory
// log or something
}
}
}
public static void main (String[] args) {
File folder = new File("./WebContent/datasets/DB_Set/");
List<File> files = addFiles(folder);
}

Get all folders with a given name

I am searching for a solution to find all folders with the same name in a given directory.
So my folder structure looks like this:
Root
| | |
android windows ios
| | | | | |
focus normal focus normal focus normal
Note: There are more folders between the clients and the iconsets, that's why I need recursion.
I want to get a ArrayList with all the pathes of e.g. Normal folders.
Although recursion confuses me a lot all the time I couldnt to it.
This was my first try, which should return ALL contained directories in the Root folder (parameter path). The String iconset should define the name of the searched folder afterwards.
private static ArrayList<String> getAllIconSetFolders(String path, String iconset) {
ArrayList<String> pathes = new ArrayList<String>();
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file != null && file.isDirectory()) {
pathes.addAll(getAllIconSetFolders(file.getAbsolutePath(), iconset));
}
}
return pathes;
}
It will return an empty ArrayList in this case.
How can I get all paths for (The normal folders when String iconset = "normal") so my result would look like:
"Root/android/[...]/normal"
"Root/windows/[...]/normal"
"Root/ios/[...]/normal"
I've just tested the following code and it appears to work correctly:
public static List<File> findDirectoriesWithSameName(String name, File root) {
List<File> result = new ArrayList<>();
for (File file : root.listFiles()) {
if (file.isDirectory()) {
if (file.getName().equals(name)) {
result.add(file);
}
result.addAll(findDirectoriesWithSameName(name, file));
}
}
return result;
}
Your original code was almost there, you just omitted the part where you actually add matching directories to your result list.
Tested with:
C:\tmp\foo
C:\tmp\foo\bar
C:\tmp\foo\baz
C:\tmp\foo\baz\foo
C:\tmp\foo\baz\foo\bar
Using
public static void main(String[] args) throws Exception {
List<File> files = findDirectoriesWithSameName("foo", new File("C:\\tmp"));
for (File f :files) {
System.out.println(f);
}
}
Output:
C:\tmp\foo
C:\tmp\foo\baz\foo
You need to add the directory name to pathes otherwise it will always be empty. Your code should be something like:
private static List<String> getAllIconSetFolders(String path, String iconset)
{
List<String> pathes = new ArrayList<String>();
File folder = new File(path);
for (File file : folder.listFiles())
{
if (file.isDirectory())
{
if (file.getName().equals(iconset))
{
pathes.add(file.getAbsolutePath());
}
else
{
pathes.addAll(getAllIconSetFolders(file.getAbsolutePath(), iconset));
}
}
}
return pathes;
}
This assumes the iconset is the name of the directory you are looking for and that that directories with that name can exist multiple times in the directory tree.
While searching for directory inside a directory, one elegant way is to use FileFilter or for name matching use FileNameFilter. On top of it you apply standard recursive ways the complete solution would be:
static void test()
{
File f = new File("e:\\folder");
List<File> res = new ArrayList<File>();
search(f, res, "normal");
System.out.println(res);
search(f, res, "focus");
System.out.println(res);
}
static void search(File f, List<File> res, final String search)
{
if(f.isDirectory())
{
File[] result = f.listFiles(new FilenameFilter()
{
public boolean accept(File file, String name)
{
return file.isDirectory() && name.equals(search);
}
});
if(result != null)
{
for(File file : result)
{
res.add(file);
}
}
//search further recursively
File[] allFiles = f.listFiles();
if(allFiles != null)
{
for(File file: allFiles)
{
search(file, res, search);
}
}
}
}
Or you can extend FileNameFilter as say NormalDirFilter or FocusDirFilter where you can hardcode specific folder search name. Use instances of these specific filters while listing file during recursion.
Tested. Works. Need Java 7.
public static void main(String[] args) {
List<String> paths = new ArrayList<String>();
getAllFolders("/path/to/folder", "normal", paths);
}
private static void getAllFolders(String path, String folderName, List<String> paths) throws Exception {
Path mainPath = Paths.get(path);
Iterator<Path> stream = Files.newDirectoryStream(mainPath).iterator();
while(stream.hasNext()) {
Path currentPath = stream.next();
String currentFolderName = currentPath.getFileName().toString();
if(currentFolderName.equals(folderName)) {
paths.add(currentPath.toString());
}
getAllFolders(currentPath.toString(), folderName, paths);
}
}
If you have this structure, could you not do
public static List<File> subdirectories(File root, String toFind) {
List<File> ret = new ArrayList<File>();
for(File dir : root.listFiles()) {
File dir2 = new File(dir, toFind);
if (dir2.isDirectory())
ret.add(dir2);
}
return ret;
}

how I got all of text files in directory and sub directory?

I know how to create list to contain all of files in directory by this code
String path = "c:/test";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
but if i have directory has files and sub directory and the sub directory has files and sub-sub directory and so on..
how I create list contain all files in directory and sub directory ?
You could do like this:
protected java.util.List<File> setDirMap(File inputDir) {
if (!inputDir.isDirectory()) {
throw new IllegalArgumentException("Input File is not a directory");
}
Set<File> ans = new HashSet<File>();
ans.add(inputDir);
File[] dir = inputDir.listFiles(new FileFilter() {
#Override
/**
* Returns true if pathname is a directory. False if not
*/
public boolean accept(File pathname) {
if (pathname.isDirectory()) {
return true;
} else {
return false;
}
}
});
ans.addAll(Arrays.asList(dir));
for (File current : dir) {
ans.addAll(setDirMap(current));
}
return new ArrayList<File>(ans);
}
This returns all directories and sub-directories. You can then check each directory for whatever you want
Try this code, this uses recursion....
import java.io.File;
import java.util.ArrayList;
public class FindIt {
private ArrayList<String> arList = new ArrayList<String>();
public void find(String s) {
File f = new File(s);
File[] fArr = f.listFiles();
for (File x : fArr) {
if (x.isFile()) {
if (x.getName().endsWith(".txt")) {
arList.add(x.getName());
}
else {
continue;
}
}
else {
find(x.getAbsolutePath());
}
}
}
public static void main(String[] args) {
FindIt f = new FindIt();
f.find("D:\\xtop");
for (String fileName : f.arList) {
System.out.println(fileName);
}
}
}

How to read all files in a folder from Java?

Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
How to read all the files in a folder through Java? It doesn't matter which API.
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
Files.walk API is available from Java 8.
try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {
paths
.filter(Files::isRegularFile)
.forEach(System.out::println);
}
The example uses try-with-resources pattern recommended in API guide. It ensures that no matter circumstances the stream will be closed.
File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println(file.getName());
}
}
In Java 8 you can do this
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
which will print all files in a folder while excluding all directories. If you need a list, the following will do:
Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.collect(Collectors.toList())
If you want to return List<File> instead of List<Path> just map it:
List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder"))
.filter(Files::isRegularFile)
.map(Path::toFile)
.collect(Collectors.toList());
You also need to make sure to close the stream! Otherwise you might run into an exception telling you that too many files are open. Read here for more information.
All of the answers on this topic that make use of the new Java 8 functions are neglecting to close the stream. The example in the accepted answer should be:
try (Stream<Path> filePathStream=Files.walk(Paths.get("/home/you/Desktop"))) {
filePathStream.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
}
});
}
From the javadoc of the Files.walk method:
The returned stream encapsulates one or more DirectoryStreams. If
timely disposal of file system resources is required, the
try-with-resources construct should be used to ensure that the
stream's close method is invoked after the stream operations are completed.
One remark according to get all files in the directory.
The method Files.walk(path) will return all files by walking the file tree rooted at the given started file.
For instance, there is the next file tree:
\---folder
| file1.txt
| file2.txt
|
\---subfolder
file3.txt
file4.txt
Using the java.nio.file.Files.walk(Path):
Files.walk(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
Gives the following result:
folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt
To get all files only in the current directory use the java.nio.file.Files.list(Path):
Files.list(Paths.get("folder"))
.filter(Files::isRegularFile)
.forEach(System.out::println);
Result:
folder\file1.txt
folder\file2.txt
import java.io.File;
public class ReadFilesFromFolder {
public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
static String temp = "";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
// System.out.println("Reading files under the folder "+folder.getAbsolutePath());
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
In Java 7 and higher you can use listdir
Path dir = ...;
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file: stream) {
System.out.println(file.getFileName());
}
} 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);
}
You can also create a filter that can then be passed into the newDirectoryStream method above
DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
public boolean accept(Path file) throws IOException {
try {
return (Files.isRegularFile(path));
} catch (IOException x) {
// Failed to determine if it's a file.
System.err.println(x);
return false;
}
}
};
For other filtering examples, [see documentation].(http://docs.oracle.com/javase/tutorial/essential/io/dirs.html#glob)
private static final String ROOT_FILE_PATH="/";
File f=new File(ROOT_FILE_PATH);
File[] allSubFiles=f.listFiles();
for (File file : allSubFiles) {
if(file.isDirectory())
{
System.out.println(file.getAbsolutePath()+" is directory");
//Steps for directory
}
else
{
System.out.println(file.getAbsolutePath()+" is file");
//steps for files
}
}
Just walk through all Files using Files.walkFileTree (Java 7)
Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println("file: " + file);
return FileVisitResult.CONTINUE;
}
});
If you want more options, you can use this function which aims to populate an arraylist of files present in a folder. Options are : recursivility and pattern to match.
public static ArrayList<File> listFilesForFolder(final File folder,
final boolean recursivity,
final String patternFileFilter) {
// Inputs
boolean filteredFile = false;
// Ouput
final ArrayList<File> output = new ArrayList<File> ();
// Foreach elements
for (final File fileEntry : folder.listFiles()) {
// If this element is a directory, do it recursivly
if (fileEntry.isDirectory()) {
if (recursivity) {
output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
}
}
else {
// If there is no pattern, the file is correct
if (patternFileFilter.length() == 0) {
filteredFile = true;
}
// Otherwise we need to filter by pattern
else {
filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
}
// If the file has a name which match with the pattern, then add it to the list
if (filteredFile) {
output.add(fileEntry);
}
}
}
return output;
}
Best, Adrien
File directory = new File("/user/folder");
File[] myarray;
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
File path=myarray[j];
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String s = "";
while (br.ready()) {
s += br.readLine() + "\n";
}
}
nice usage of java.io.FileFilter as seen on https://stackoverflow.com/a/286001/146745
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
static File mainFolder = new File("Folder");
public static void main(String[] args) {
lf.getFiles(lf.mainFolder);
}
public void getFiles(File f) {
File files[];
if (f.isFile()) {
String name=f.getName();
} else {
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
I think this is good way to read all the files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
files.add(path.get(i));
}
}
}
if(input.isFile())
{
files.add(input);
}
}
Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:
import java.io.File;
public class List {
public static void main(String[] args) {
for (String f : args) {
listDir(f);
}
}
private static void listDir(String dir) {
File f = new File(dir);
File[] list = f.listFiles();
if (list == null) {
return;
}
for (File entry : list) {
System.out.println(entry.getName());
if (entry.isDirectory()) {
listDir(entry.getAbsolutePath());
}
}
}
}
While I do agree with Rich, Orian and the rest for using:
final File keysFileFolder = new File(<path>);
File[] fileslist = keysFileFolder.listFiles();
if(fileslist != null)
{
//Do your thing here...
}
for some reason all the examples here uses absolute path (i.e. all the way from root, or, say, drive letter (C:\) for windows..)
I'd like to add that it is possible to use relative path as-well.
So, if you're pwd (current directory/folder) is folder1 and you want to parse folder1/subfolder, you simply write (in the code above instead of ):
final File keysFileFolder = new File("subfolder");
Java 8 Files.walk(..) is good when you are soore it will not throw Avoid Java 8 Files.walk(..) termination cause of ( java.nio.file.AccessDeniedException ) .
Here is a safe solution , not though so elegant as Java 8Files.walk(..) :
int[] count = {0};
try {
Files.walkFileTree(Paths.get(dir.getPath()), new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
System.out.printf("Visiting file %s\n", file);
++count[0];
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
System.err.printf("Visiting failed for %s\n", file);
return FileVisitResult.SKIP_SUBTREE;
}
#Override
public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
System.out.printf("About to visit directory %s\n", dir);
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
void getFiles(){
String dirPath = "E:/folder_name";
File dir = new File(dirPath);
String[] files = dir.list();
if (files.length == 0) {
System.out.println("The directory is empty");
} else {
for (String aFile : files) {
System.out.println(aFile);
}
}
}
package com;
import java.io.File;
/**
*
* #author ?Mukesh
*/
public class ListFiles {
static File mainFolder = new File("D:\\Movies");
public static void main(String[] args)
{
ListFiles lf = new ListFiles();
lf.getFiles(lf.mainFolder);
long fileSize = mainFolder.length();
System.out.println("mainFolder size in bytes is: " + fileSize);
System.out.println("File size in KB is : " + (double)fileSize/1024);
System.out.println("File size in MB is :" + (double)fileSize/(1024*1024));
}
public void getFiles(File f){
File files[];
if(f.isFile())
System.out.println(f.getAbsolutePath());
else{
files = f.listFiles();
for (int i = 0; i < files.length; i++) {
getFiles(files[i]);
}
}
}
}
Just to expand on the accepted answer I store the filenames to an ArrayList (instead of just dumping them to System.out.println) I created a helper class "MyFileUtils" so it could be imported by other projects:
class MyFileUtils {
public static void loadFilesForFolder(final File folder, List<String> fileList){
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
loadFilesForFolder(fileEntry, fileList);
} else {
fileList.add( fileEntry.getParent() + File.separator + fileEntry.getName() );
}
}
}
}
I added the full path to the file name.
You would use it like this:
import MyFileUtils;
List<String> fileList = new ArrayList<String>();
final File folder = new File("/home/you/Desktop");
MyFileUtils.loadFilesForFolder(folder, fileList);
// Dump file list values
for (String fileName : fileList){
System.out.println(fileName);
}
The ArrayList is passed by "value", but the value is used to point to the same ArrayList object living in the JVM Heap. In this way, each recursion call adds filenames to the same ArrayList (we are NOT creating a new ArrayList on each recursive call).
There are many good answers above, here's a different approach: In a maven project, everything you put in the resources folder is copied by default in the target/classes folder. To see what is available at runtime
ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader();
URL resource = contextClassLoader.getResource("");
File file = new File(resource.toURI());
File[] files = file.listFiles();
for (File f : files) {
System.out.println(f.getName());
}
Now to get the files from a specific folder, let's say you have a folder called 'res' in your resources folder, just replace:
URL resource = contextClassLoader.getResource("res");
If you want to have access in your com.companyName package then:
contextClassLoader.getResource("com.companyName");
You can put the file path to argument and create a list with all the filepaths and not put it the list manually. Then use a for loop and a reader. Example for txt files:
public static void main(String[] args) throws IOException{
File[] files = new File(args[0].replace("\\", "\\\\")).listFiles(new FilenameFilter() { #Override public boolean accept(File dir, String name) { return name.endsWith(".txt"); } });
ArrayList<String> filedir = new ArrayList<String>();
String FILE_TEST = null;
for (i=0; i<files.length; i++){
filedir.add(files[i].toString());
CSV_FILE_TEST=filedir.get(i)
try(Reader testreader = Files.newBufferedReader(Paths.get(FILE_TEST));
){
//write your stuff
}}}
package com.commandline.folder;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FolderReadingDemo {
public static void main(String[] args) {
String str = args[0];
final File folder = new File(str);
// listFilesForFolder(folder);
listFilesForFolder(str);
}
public static void listFilesForFolder(String str) {
try (Stream<Path> paths = Files.walk(Paths.get(str))) {
paths.filter(Files::isRegularFile).forEach(System.out::println);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
We can use org.apache.commons.io.FileUtils, use listFiles() mehtod to read all the files in a given folder.
eg:
FileUtils.listFiles(directory, new String[] {"ext1", "ext2"}, true)
This read all the files in the given directory with given extensions, we can pass multiple extensions in the array and read recursively within the folder(true parameter).
public static List<File> files(String dirname) {
if (dirname == null) {
return Collections.emptyList();
}
File dir = new File(dirname);
if (!dir.exists()) {
return Collections.emptyList();
}
if (!dir.isDirectory()) {
return Collections.singletonList(file(dirname));
}
return Arrays.stream(Objects.requireNonNull(dir.listFiles()))
.collect(Collectors.toList());
}
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AvoidNullExp {
public static void main(String[] args) {
List<File> fileList =new ArrayList<>();
final File folder = new File("g:/master");
new AvoidNullExp().listFilesForFolder(folder, fileList);
}
public void listFilesForFolder(final File folder,List<File> fileList) {
File[] filesInFolder = folder.listFiles();
if (filesInFolder != null) {
for (final File fileEntry : filesInFolder) {
if (fileEntry.isDirectory()) {
System.out.println("DIR : "+fileEntry.getName());
listFilesForFolder(fileEntry,fileList);
} else {
System.out.println("FILE : "+fileEntry.getName());
fileList.add(fileEntry);
}
}
}
}
}
list down files from Test folder present inside class path
import java.io.File;
import java.io.IOException;
public class Hello {
public static void main(final String[] args) throws IOException {
System.out.println("List down all the files present on the server directory");
File file1 = new File("/prog/FileTest/src/Test");
File[] files = file1.listFiles();
if (null != files) {
for (int fileIntList = 0; fileIntList < files.length; fileIntList++) {
String ss = files[fileIntList].toString();
if (null != ss && ss.length() > 0) {
System.out.println("File: " + (fileIntList + 1) + " :" + ss.substring(ss.lastIndexOf("\\") + 1, ss.length()));
}
}
}
}
}
/**
* Function to read all mp3 files from sdcard and store the details in an
* ArrayList
*/
public ArrayList<HashMap<String, String>> getPlayList()
{
ArrayList<HashMap<String, String>> songsList=new ArrayList<>();
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put(
"songTitle",
file.getName().substring(0,
(file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which have a .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter
{
#Override
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
You can filter any textfiles or any other extension ..just replace it with .MP3
This will Read Specified file extension files in given path(looks sub folders also)
public static Map<String,List<File>> getFileNames(String
dirName,Map<String,List<File>> filesContainer,final String fileExt){
String dirPath = dirName;
List<File>files = new ArrayList<>();
Map<String,List<File>> completeFiles = filesContainer;
if(completeFiles == null) {
completeFiles = new HashMap<>();
}
File file = new File(dirName);
FileFilter fileFilter = new FileFilter() {
#Override
public boolean accept(File file) {
boolean acceptFile = false;
if(file.isDirectory()) {
acceptFile = true;
}else if (file.getName().toLowerCase().endsWith(fileExt))
{
acceptFile = true;
}
return acceptFile;
}
};
for(File dirfile : file.listFiles(fileFilter)) {
if(dirfile.isFile() &&
dirfile.getName().toLowerCase().endsWith(fileExt)) {
files.add(dirfile);
}else if(dirfile.isDirectory()) {
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
getFileNames(dirfile.getAbsolutePath(),completeFiles,fileExt);
}
}
if(!files.isEmpty()) {
completeFiles.put(dirPath, files);
}
return completeFiles;
}
This will work fine:
private static void addfiles(File inputValVal, ArrayList<File> files)
{
if(inputVal.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(inputVal.listFiles()));
for(int i=0; i<path.size(); ++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
files.add(path.get(i));
}
}
/* Optional : if you need to have the counts of all the folders and files you can create 2 global arrays
and store the results of the above 2 if loops inside these arrays */
}
if(inputVal.isFile())
{
files.add(inputVal);
}
}

Categories