Java - Read many txt files on a folder and process them - java

I followed this question:
Now in my case i have 720 files named in this way: "dom 24 mar 2013_00.50.35_128.txt", every file has a different date and time. In testing phase i used Scanner, with a specific txt file, to do some operations on it:
Scanner s = new Scanner(new File("stuff.txt"));
My question is:
How can i reuse scanner and read all 720 files without having to set the precise name on scanner?
Thanks

Assuming you have all the files in one place:
File dir = new File("path/to/files/");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
...
s.close();
}
Note that if you have any files that you don't want to include, you can give listFiles() a FileFilter argument to filter them out.

Yes, create your file object by pointing it to a directory and then list the files of that directory.
File dir = new File("Dir/ToYour/Files");
if(dir.isDir()) {
for(File file : dir.listFiles()) {
if(file.isFile()) {
//do stuff on a file
}
}
} else {
//do stuff on a file
}

You can try this in this way
File folder = new File("D:\\DestFile");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()&&(file.getName().substring(file.getName().lastIndexOf('.')+1).equals("txt"))) {
// Scanner
}
}

File file = new File(folderNameFromWhereToRead);
if(file!=null && file.exists()){
File[] listOfFiles = file.listFiles();
if(listOfFiles!=null){
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
// DO work
}
}
}
}

Related

How to use one file from list of files [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
File folder = new File("C:/Path/Dir");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
String csvFile = file.getName();
System.out.println(csvFile);
}
}
Output:
1.csv
2.csv
3.csv
There is 3 files in my Dir so after i get all 3 of them how can i use the first one in my file reader:
//File reader
Path path = Paths.get(csvFile);
int lineCount = (int) Files.lines(path).count();
If you are specific to 1st file only then just use listOfFiles[0].getName() to get fileName.
If you are to going to take path of a file that satisfy specific condition then you can use like below :
File folder = new File("C:/Path/Dir");
File[] listOfFiles = folder.listFiles();
String csvFile = null;
for (File file : listOfFiles) {
if (file.isFile() && <condition>) {
csvFile = file.getName();
System.out.println(csvFile);
break;
}
}
listOfFiles[0] should get you the first element.
Please read some tutorials on java arrays :
https://www.javatpoint.com/array-in-java
There:
File folder = new File("C:/Path/Dir");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
String csvFile = file.getName();
System.out.println(csvFile);
// Reader (for all files)
try {
FileReader reader = new FileReader(file);
} catch (IOException e) { /* TODO */ }
// Line count (for all files)
int lineCount = (int) Files.lines(file.toPath()).count();
}
}
// Reader (for first file)
File firstFile = listOfFiles[0];
try {
FileReader reader = new FileReader(file);
} catch (IOException e) { /* TODO */ }
// Line count (for first file)
int lineCount = (int) Files.lines(firstFile.toPath()).count();
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());
}
}
then i use
listOfFiles[i] in my file reader
Sorry for been dump for a while )
When you are only interested in files (not directories or whatever) you can already specify this criteria in your File.listFiles call:
File[] files=new File("c:/tmp").listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
Or with java 8 Lambdas
File[] files=new File("c:/tmp").listFiles((f)->{return f.isFile();});
In the list of files you can pick the first one as you would do to pick the first element of an array:
System.out.println("First file:"+(files.length>0?files[0]:" no files"));
Simple, you have all files in an array of the File as
File[] listOfFiles = folder.listFiles();
So you can directly access the first file by index (index starts with 0) as follows
Path path = Paths.get(listOfFiles[0].getName());
int lineCount = (int) Files.lines(path).count();
You need to figure out two thing:first read only file not folder;second which file is the fisrt file.The follow code assume you want read file and get first file by file name in dictionary order:
private static void readFirstFile(String path) throws Exception {
File folder = new File(path);
File[] files = folder.listFiles(File::isFile);
if (null == files || files.length < 3) {
return;
}
Arrays.sort(files, Comparator.comparing(File::getName));
List<String> lines = FileUtils.readLines(files[0], "UTF-8");
lines.forEach(System.out::println);
}

How to Write the output into txt file using FileWriter

This is my java code to find the locations of files inside the directory and write them into a txt file as the output ,but after compilation the contents are not writing into txt file. please give me some solution.
public void listFilesAndFilesSubDirectories(String directoryName)
{
File directory = new File(directoryName);
List<String> list=new ArrayList<String> ();
//get all the files from a directory
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
if(file.getName().endsWith(".c")==true || file.getName().endsWith(".h")==true){
// System.out.println(file.getAbsolutePath());
list.add(file.getAbsolutePath());
}
} else if (file.isDirectory()){
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
else break;
}
try{
FileWriter fw=new FileWriter("C:/Users/Public/afreen/module.txt");
BufferedWriter out = new BufferedWriter(fw);
for(String str: list)
{
System.out.println(str);
out.write(str);
}
out.flush();
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Success....");
}
else
{
System.out.println("The directory is not exist , please enter a valid path");
}
}
The above code will take the input as the path for directory and finds the location of files which I want.But the locations are not able to write into txt file,I am not abel to find the actual reason ,please help me out to find the solution of it.
Each time your method gets called (recursively) creates a new list and add the directory name to it but that list is not the one you are printing from, try to use a shared resource. for example use a global variable or etc.

Make an Array of the Names from the Image Folder (java and Spring boot)

I've got an image folder in my resources folder and there are pictures stored.
Now I want an Array in my Java Class who has stored the names of each Picture in the folder. Later I want to test if a picture name equals a specific word, but that can I handle by myself. I just dont know, how to make the 'PictureName' Array.
I am using Spring boot with Java.
File folder = new File("C:\\path\\to\\your\\folder\\");
List<File> files = Arrays.asList(folder.listFiles());
Insert the path to the folder that contains all your images in the first line.
In files List you will find the list of all the images in your folder in objects of type File.
Every File object has the method getName() that will return the name of the image.
Try somethings like this(Check if f is file( because it can be dictionary):
File folder = new File("yourPathTofolder");
File[] listOfFiles = folder.listFiles();
for (File f: listOfFiles) {
if (f.isFile()) {
System.out.println("File " + f.getName());
}
}
It can be done easily:
File folder = new File("your_path");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if(file.isFile()){
System.out.println("File Name:" + file.getName());
}
}
You can use below code:
First provide your folder path, that will contain all the images.
File folder = new File("your/path");
Store all files in File type array variable.
File[] listOfFiles = folder.listFiles();
Iterate over variable to get filename(s)
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else {
System.out.println("Not a File..");
}
}
Full code
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else {
System.out.println("Not a File..");
}
}
Hope that helps.

find specific file type from folder and its sub folder

I am writing a method to get specific file type such as pdf or txt from folders and subfolders but I am lacking to solve this problem. here is my code
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
My current method list all files but I need specific files
For a filtered list without needing recursion through sub directories you can just do:
directory.listFiles(new FilenameFilter() {
boolean accept(File dir, String name) {
return name.endsWith(".pdf");
}});
For efficiency you could create the FilenameFilter ahead of time rather than for each call.
In this case because you want to scan sub folders too there is no point filtering the files as you still need to check for sub folders. In fact you were very nearly there:
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
if (file.getName().endsWith(".pdf")) {
System.out.println(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
if(file.getName().endsWith(".pdf")) {
//it is a .pdf file!
}
/***/
Try using the FilenameFilter interface in you function
http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html
http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - for a code that has extention filter
Use File.listFiles(FileFilter).
Example:
File[] fList = directory.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().endSwith(".pdf");
}
});
You can use apache fileUtils class
String[] exte= {"xml","properties"};
Collection<File> files = FileUtils.listFiles(new File("d:\\workspace"), exte, true);
for(File file: files){
System.out.println(file.getAbsolutePath());
}
My advice is to use FileUtils or NIO.2.
NIO.2 allows Stream with Depth-First search, for example you can print all files with a specified extension in one line of code:
Path path = Path.get("/folder");
try{
Files.walk(path).filter(n -> n.toString().endsWith(".extension")).forEach(System.out::println)
}catch(IOException e){
//Manage exception
}

How to get all the filenames in android directory?

Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.
Heres my code:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
This doesnt seem to work dont know why.
I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
change
File[] file= new File(sdCardRoot+"path");
with
File[] file= new File(sdCardRoot, "path");
and make sure the directory path exits
Just Check this:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
Since sdCardRoot is instance of File, sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path".
However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path".
Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.

Categories