Filter out the text files - java

The code separates files from directories.
I am trying to filter out the text files(.txt) and print out the files that remain.
I don't want the text files to be printed at all. I want the code to be implemented after the if statement if (listOfFiles[i].isFile()) { so after it checks to see if a given value is an actual file and then to determine if it is a text file, and if either test fails, add it to the listOfFiles array list.
Need help
import java.io.BufferedInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Exc_3 {
public static void main(String[] args) {
File folder = new File("C:\\Users\\skyla\\Desktop");
File[] listOfFiles = folder.listFiles();
List<String> files = new ArrayList<>();
List<String> directories = new ArrayList<>();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files.add(listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
directories.add(listOfFiles[i].getName());
}
}
System.out.println("List of files :\n---------------");
for (String fName : files)
System.out.println(fName);
System.out.println("\nList of directories :\n---------------------");
for (String dName : directories)
System.out.println(dName);
}
}

Since you're only checking if the file extension is ".txt" then you can check the name with String.endsWith(".txt")
if (listOfFiles[i].isFile()) {
if (listOfFiles[i].getName().endsWith(".txt")) {
files.add(listOfFiles[i].getName());
}
}

Why don't you use the piece of code below. You can also use it into a function that checks whether your files is a .txt file by producing a boolean true if mimeType="text/plain"
Path path = FileSystems.getDefault().getPath("myFolder", "myFile");
String mimeType = Files.probeContentType(path);
Good luck

Related

SubFolders not showing text files - JAVA

So I'm trying to make a student attendance by reading text files(all files are filled with names of students) from a folder[main folder is named Attendance], which folder has 2 sub-folders, and my program is not showing any text file, below is the code where I've created a File where, the path of the main folder is saved, and then created a List to store all files :
File folder = new File("C:\\Users\\HP\\IdeaProjects\\AdaptiveJava\\src\\StudentAttendance\\Attendance");
List<File> allFiles = Arrays.asList(folder.listFiles());
and so I have a method to print all text files that are inside the main folder :
public static void printFileNames(List<File> fileList){
for(int i = 0; i < fileList.size();i++){
if(fileList.get(i).isFile()){
System.out.println(fileList.get(i).getName());
}
}
}
but is not printing anything, but when I change the file path e.g to
File folder = new File("C:\\Users\\HP\\IdeaProjects\\AdaptiveJava\\src\\StudentAttendance\\Attendance\\SubFolder1");
it prints all text files that are inside sub-folder and vice versa.
What am I doing wrong here? How should multiple text-files be read from sub-folders?
You should also list the files in the subfolder, the method listFiles() only list the files relative to the folder you are in, so you can iterate over the first list of files and then list the files for each subfolder, this is an approach using java 8 streams:
List<File> allFiles = Arrays.stream(folder.listFiles())
.filter(File::isDirectory)
.flatMap(f -> Arrays.stream(f.listFiles()))
.collect(Collectors.toList());
You can also accomplish that using a for to iterate over the result of the first listFiles call, and call that method for every of the files asking first if it's a directory, something like this:
List<File> allFiles = new ArrayList<>();
for (File f : folder.listFiles()) {
if (f.isDirectory()) {
allFiles.addAll(Arrays.asList(f.listFiles()));
}
}
Your code should work. If i use the following code, it prints all filenames in the subfolder filesToPrint of the current working directory.
package test.print.files;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class PrintFiles
{
public static void main(String[] args)
{
File folder = new File("./filesToPrint");
List<File> allFiles = Arrays.asList(folder.listFiles());
printFileNames(allFiles);
}
public static void printFileNames(List<File> fileList)
{
for (int i = 0; i < fileList.size(); i++)
{
if (fileList.get(i).isFile())
{
System.out.println(fileList.get(i).getName());
}
}
}
}
example directory:
c:\filesToPrint\file1.txt
file2.txt
output:
file1.txt
file2.txt

Scanning for files that contain variable name

I have a simple piece of code that currently uses tesseract OCR to read the text in any given image and then count how many lines it produces. However, I would like to search a directory for any document containing a string (such as M000123456) and return a number of how many documents contain that in their name and compare that to the number tesseract output. The documents are named liked so: M000123456_V987654_05-07-2000.pdf. What's the best way to do this?
import java.io.File;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Main {
public static void main(String[] args) throws TesseractException {
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C:\\Users\\mmx0409\\Downloads\\Tess4J-3.4.8-src\\Tess4J\\tessdata");
// the path of your tess data folder
// inside the extracted file
String text
= tesseract.doOCR(new File("C:\\Users\\mmx0409\\Downloads\\testimage.png"));
// path of your image file
System.out.print(text);
System.out.println(text.lines().count()); // count the number of lines tesseract saw
}
}
You can use the below function to count the number of the document which is having searchString in its name.
public int countDocuments(String directoryPath, String searchString) {
File folder = new File(directoryPath);
File[] listOfFiles = folder.listFiles();
int count = 0;
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String fileName = listOfFiles[i].getName();
if (fileName.contains(searchString)) {
count++;
}
}
}
return count;
}

Remove certain characters from a directory's name in Java

So I wrote a little program to use on a Unix machine that has to get all the names of the files and folders in a directory where it is stored and then remove all the characters from them. These characters (or a character) will be defined by a user. Use case: I put the program in the directory containing various useless files and directories named, for example, "NaCl2!!!!!!!!!", "H2O!", "O2" and "Lithium!!!!!" and I "ask" it to get rid of all the bangs in all the directores' names so it will result in this:
ls
NaCl2 H2O O2 Lithium Unreal3.zip
Ok I guess you get it. So here's the code and it doesn't compile (
DirRename.java:18: error: method renameTo in class File cannot be applied to given types;
tempDir.renameTo(name);
). I guess this error is caused with a substantial problem in my code. Is there a way to get it working, can you tell me, please?
import java.io.*; import java.util.Scanner;
class DirRename {
public static void main(String[] s) {
//DECLARING
String name, curDir, annoyngChar;
Scanner scan = new Scanner(System.in);
//WORKING
curDir = System.getProperty("user.dir");
File dir = new File(curDir);
File[] listOfFiles = dir.listFiles();
System.out.print("Type a character (or a line of them) that you want to remove from directories' names:");
annoyngChar = scan.nextLine();
System.out.println("\nAll directories will get rid of " + annoyngChar + " in their names.");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() ) {
File tempDir = listOfFiles[i];
name = tempDir.getName().replaceAll(annoyngChar, "");
tempDir.renameTo(name);
}
}
}
}
Need to say, the program is unfinished, I am sorry for that.
File.renameTo(File dest) takes a File parameter, not a String. So, you need to create a File instance with the correct path (using the new name), and pass that instance to renameTo.
Try this (not tested):
import java.io.*; import java.util.Scanner;
class DirRename {
public static void main(String[] s) {
//DECLARING
String name, curDir, annoyngChar;
Scanner scan = new Scanner(System.in);
//WORKING
curDir = System.getProperty("user.dir");
File dir = new File(curDir);
File[] listOfFiles = dir.listFiles();
System.out.print("Type a character (or a line of them) that you want to remove from directories' names:");
annoyngChar = scan.nextLine();
System.out.println("\nAll directories will get rid of " + annoyngChar + " in their names.");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() ) {
File f = listOfFiles[i];
String oldName = f.getName();
name = oldName.replaceAll(annoyngChar, "");
if (!oldName.equals(name)) {
File newF = new File(dir, name);
f.renameTo(newF);
}
}
}
}
}
Alternatively, you can use Files.move to rename the file. The documentation has an example of how to rename a file while keeping it in the same directory.

Java - Deleting files and folder of parent path recursively

I'm creating a java program which takes parent path and deletes all the files and folders in the given path. I'm able to delete files and folder's files inside another folder in the parent folder but not able to delete folders at 3rd level.
Here's my code:
package com.sid.trial;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
public class DeleteFilesOfDirectoryWithFilters {
public static void main(String[] args) {
String parentPath = "D:\\tester";
List<String> folderPaths = deleteFiles(parentPath);
deleteFolders(folderPaths);
}
public static void deleteFolders(List<String> folderPaths) {
for(String path : folderPaths){
File folder = new File(path);
if(folder.delete())
System.out.println("Folder "+folder.getName()+" Successfully Deleted.");
}
}
public static List<String> deleteFiles(String path){
File folder = new File(path);
File[] files = folder.listFiles();
List<String> folderPaths = new ArrayList<String>();
String folderPath = path;
if(files.length == 0){
System.out.println("Directory is Empty or No FIles Available to Delete.");
}
for (File file : files) {
if (file.isFile() && file.exists()) {
file.delete();
System.out.println("File "+file.getName()+" Successfully Deleted.");
} else {
if(file.isDirectory()){
folderPath = file.getAbsolutePath();
char lastCharacter = path.charAt(path.length()-1);
if(!(lastCharacter == '/' || lastCharacter == '\\')){
folderPath = folderPath.concat("\\");
}
/*folderPath = folderPath.concat(file.getName());*/
System.out.println(folderPath);
folderPaths.add(folderPath);
}
}
}
for(String directoryPath : folderPaths){
List<String> processedFiles = new ArrayList<String>();
processedFiles = deleteFiles(directoryPath);
folderPaths.addAll(processedFiles);
}
return folderPaths;
}
}
You can use the ""new"" Java File API with Stream API:
Path dirPath = Paths.get( "./yourDirectory" );
Files.walk( dirPath )
.map( Path::toFile )
.sorted( Comparator.comparing( File::isDirectory ) )
.forEach( File::delete );
Note that the call to sorted() method is here to delete all files before directories.
About one statement, and without any third party library ;)
You should consider using Apache Commons-IO. It has a FileUtils class with a method deleteDirectory that will recursively delete.
Note: Apache Commons-IO (as for version 2.5) provides utilities only for legacy java.io API (File and friends), not for Java 7+ java.nio API (Path and friends).
You can recursively traverse through the folder and delete each file one by one. After deleting all the files in one folder, delete the folder. Something similar to following code should work:
public void delete(File path){
File[] l = path.listFiles();
for (File f : l){
if (f.isDirectory())
delete(f);
else
f.delete();
}
path.delete();
}
You can do the following, your recursion is longer than needed.
public static void deleteFiles (File file){
if(file.isDirectory()){
File[] files = file.listFiles(); //All files and sub folders
for(int x=0; files != null && x<files.length; x++)
deleteFiles(files[x]);
}
else
file.delete();
}
Explanation:
When invoke deleteFiles() on a file, the else statement gets triggered, the single file will be deleted with no recursion.
When invoke deleteFiles() on a folder, the if-statement gets triggered.
Get all the entries (files of folders residing in the folder) as an array
If there exist sub-entries, for each entry, recursively delete the sub-entry (the same process (1 and 2) repeats).
Be careful when implementing deletion of file and folders. You may want to print out all the files and folders name first instead of deleting them. Once confirmed it is working correctly, then use file.delete().

Use Java to find a File within a directory using only a Name

I'm trying to write this script that takes an Excel sheet, gets all the names of files from the cells, and moves each of those files to a specific folder. I've already got most of the code done, I just need to be able to search for each file in the source directory using just its title. Another problem is that I'm searching for multiple file types (.txt, .repos, .xlsx, .xls, .pdf, and some files don't have extensions), I only can search by the file name without the extension.
In my findAndMoveFiles method, I've got an ArrayList of each File and a Guava Multimap of XSSFCells to Strings (a cell is one cell from the Excel file and a String is the name of the folder it needs to go into, one to many relationship) as parameters. What I've got right now for the method is this.
public static void findAndMoveFiles(List<File> files, Multimap<XSSFCell, String> innerCells) {
// For each file, get its values (folders), and put that file in each of those folders
for (XSSFCell cell : innerCells.keySet()) {
// find the file in the master directory
//Finder f = new Finder();
//if (f.canBeFound(FOLDER, cell.getStringCellValue())) {
File file = find(FOLDER, cell.getStringCellValue());
//System.out.println(file.getAbsolutePath());
//List<String> values = new ArrayList(innerCells.get(cell));
/*for (String folder : values) {
File copy = file;
if (copy != null) {
System.out.println(folder);
System.out.println(copy.getAbsolutePath());
if (copy.renameTo(new File("C:\\strobell\\" + folder + "\\" + copy.getAbsolutePath()))) {
System.out.println(copy.getName() + " has been moved successfully.");
} else {
System.out.println(copy.getName() + " has failed to move.");
}
}
}*/
//}
}
}
public static File find(File dir, String fileName) {
String files = "";
File[] listOfFiles = dir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getAbsolutePath();
if (files.equals(fileName)) {
return listOfFiles[i];
}
}
}
return null;
}
I commented out parts because it wasn't working. I was getting NullPointerExceptions because some files were being returned as null. I know that it's returning null, but each file should be found.
If there are any 3rd party libraries that can do this, that would be amazing, I've been racking my brain on how to do this properly.
Instead of
File[] listOfFiles = dir.listFiles();
use
File[] listOfFiles = dir.list(new FileNameFilter() {
public boolean accept(File dir, String name) {
if( /* code to check if file name is ok */ ) {
return true;
}
return false;
}
}););
Then you can code your logic on the file names in the condition.

Categories