Java how to read files recursive - java

I want to read all files recursive inside a given path and show the path and Byte size in the output of every single File.

public class ReadFilesInPathRecursion {
public void listFiles (String startDir) {
File dir = new File(startDir);
File[] files = dir.listFiles();
if (files!=null && files.length >= 0) {
for(File file : files) {
if(file.isDirectory()) {
listFiles(file.getAbsolutePath()); // Recursion (absolute)
} else {
System.out.println(file.getName() + " (size in bytes: " + file.length() + ") " + "(path: " + file.getAbsoluteFile() + ")");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ReadFilesInPathRecursion test = new ReadFilesInPathRecursion();
String startDir = sc.next();
test.listFiles(startDir);
}

Related

ifFile Does not recognize csv, pl, sh, xml files

I'm building an array of a recursive search of a directory. That part works great, but when trying to determine if a file is a file, it only adds .txt files into the array, and skips over files like csv, pl, sh, xml and so on. Is the something I can do to fix this? here is the code I'm working with.
public static ArrayList<Object> listDirectory(String directory) {
Object sbytes;
File dir = new File((String) directory);
File[] firstLevelFiles = dir.listFiles();
ArrayList<Object> array = new ArrayList <Object>();
if (firstLevelFiles != null) {
for (File aFile : firstLevelFiles) {
//if (aFile.isFile()) {
if (! aFile.isDirectory()) {
System.out.println("[" + aFile.getAbsolutePath() + "]");
long bytes = aFile.length();
if (bytes > 1000) {
sbytes = bytes / 1000 + " Kb";
} else if (bytes > 1000000){
sbytes = bytes / 1000000 + " Mb";
} else {
sbytes = bytes + " bytes";
}
Object fileName = aFile.getName();
Object nameAndSize = fileName + " " + sbytes;
array.add(nameAndSize);
} else {
ArrayList<Object> deeperList = listDirectory(aFile.getAbsolutePath());
array.addAll(deeperList);
}
}
}
return array;
}

how to delete file based on name length

I have a list of files with same suffix , the name of files contain date and file type like this : year-month-day_filetype .. except one of them doesn't contain day ( year-month_filetype ) -you can see the picture - .. I need to delete that one doesn't contain day .. please help .. many thanks
private void scanFolder(final String fileTypename, File currentFolder, File outputFolder) {
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileTypename, file, outputFolder);
} else {
copy(file, outputFolder);
}
}
for (File f : outputFolder.listFiles()) {
if (f.getName().contains("CW")) {
f.delete();
}
System.out.println("Processing " + outputFolder.listFiles() + " Deleted ... ");
}
}
So you need a function to check if your string is the format you expect but missing the day. This should do the trick.
private boolean missingDay(String filename){
boolean result = false;
String[] parts = filename.split("_",3);
if (parts.length == 3){
String[] dateParts = parts[1].split("-",3);
if (dateParts.length<3){
result = true;
}
}
return result;
}
Then you'll say something like:
if (f.getName().contains("CW") || missingDay(f.getName())
private void scanFolder(final String fileTypename, File currentFolder, File outputFolder){
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileTypename, file, outputFolder);
}else {
copy(file, outputFolder);
}
}
for (File f : outputFolder.listFiles())
{
if (f.getName().contains("CW") || missingDay(f.getName())){
f.delete();}
System.out.println("Processing " + outputFolder.listFiles() + " Deleted ... ");
}
}
private boolean missingDay(String filename){
boolean result = false;
String[] parts = filename.split("_",3);
if (parts.length == 3){
String[] dateParts = parts[1].split("-",3);
if (dateParts.length<3){
result = true;
}
}
return result;
}

How to get the path of a file but without the actual file name

For example C:\Desktop and not C:\Desktop\file.txt.
Here's the code, what can i do to get only the path excluding the actual name of the file or do i have to mechanically remove the name part(String) with the split("\") method.
import java.io.*;
public class FilesInfo {
File file = new File("C:\\Users\\CCKS\\Desktop\\1");
public void viewFiles() throws IOException {
File[] files = file.listFiles();
String path = "";
for(int i = 0; i < files.length; i++){
if(!files[i].isDirectory()){
System.out.println("[DIRECTORY]" + files[i].getPath() + " [NAME] " + files[i].toString() + " [SIZE] " + files[i].length() + "KB");
} else {
path = files[i].getAbsolutePath();
file = new File(path);
}
}
if(path.equals("")){
return;
} else {
viewFiles();
}
}
public static void main(String [] args){
try {
new FilesInfo().viewFiles();
} catch (Exception e){
e.printStackTrace();
}
}
}
Like this,
File file = new File("C:\Desktop\file.txt");
String parentPath= file.getParent();
File file = new File( "C:/testDir/test1.txt" );
String justPath = file.getParent();

Converting working code into a recursive method

Hi guys I needed to create a method to display current directory, files, subdirectories and the files of those subdirectories given a file the user has to choose. I accomplished the task and the fallowing code is printing the appropriated output. It is printing from the f.getParentFile() down, that is what want. Now I want to use recursion instead. I am trying to learn the concept of recursion. I know you need a base case and then your inductive step, but when I try to modify my code into recursive I get an infinite loop when it hits the first subdirectory. Any feedback will be appreciated.
NON-Recursive Working code
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
File[] listFiles = list[i].getAbsoluteFile().listFiles();
for (int j = 0; j < listFiles.length; j++)
{
System.out.println("\t\tSubdirectory files: " + listFiles[j].getName() + "\tsize :" + (listFiles[j].length()/1024) + "KB" );
}
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
Attempting Recursion
static void listFiles(File f)
{
try
{
if (f.exists())
{
File dir = f.getParentFile();
if (dir.isDirectory())
{
System.out.println("Directory: " + dir );
File[] list = dir.listFiles();
for (int i = 0; i < list.length; i++)
{
if (list[i].isDirectory())
{
System.out.println("\tSubdirectory: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
listFiles(list[i].getAbsoluteFile());
}
else if (list[i].isFile())
{
System.out.println("\tFiles: " + list[i].getName() + "\tsize :" + (list[i].length()/1024) + "KB" );
}
}
}
}
else throw new FileNotFoundException("File ******** does not exists");
}
catch(NullPointerException | FileNotFoundException e)
{
e.printStackTrace();
}
}
It is really really simple :)
public static void main(String[] args) {
filesInFolder("./");
}
public static void filesInFolder(String filename) {
File dir = new File(filename);
for (File child : dir.listFiles()) {
System.out.println(child.getAbsolutePath());
if (child.isDirectory()){
filesInFolder(child.getAbsolutePath());
}
}
}

Detecting the last folder from a list

I have several files, thing is that i need to know which one was the last created according to the numbers I give them automatically.
For example if i have: file1, file2, file3 I want to receive the file3. I can't do this with "last modified" because I have other folders and files in the same directory.
Also to this last file I would like to increment his number in 1.
Put the files in a list and sort it lexically, then take the last one.
Ofcourse you have to filter out the ones you are looking for with regex or contains/startswith/endswith
Here is an alternate simple solution.
import java.io.File;
public class FileUtility {
private static final String FOLDER_PAHT = "D:\\Test";
private static final String FILE_PREFIX = "file";
/**
* #param args
*/
public static void main(String[] args) {
int lastFileNumber = getLastFileNumber();
System.out.println("In folder " + FOLDER_PAHT + " last file is " + FILE_PREFIX + lastFileNumber);
if(incrementFileNumber(lastFileNumber)) {
System.out.println("After incrementing the last file becomes : FILE_PREFIX" + lastFileNumber + 1);
} else {
System.out.println("Some error occured while updating file number.");
}
}
private static int getLastFileNumber(){
int maxFileNumber = 0;
File folder = new File(FOLDER_PAHT);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String fileName = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && fileName.contains(FILE_PREFIX)) {
try {
int fileNumber = Integer.parseInt(fileName.substring(FILE_PREFIX.length(), fileName.indexOf(".")));
if(maxFileNumber < fileNumber) {
maxFileNumber = fileNumber;
}
} catch (NumberFormatException e) {
// Because there can be files with starting name as FILE_PREFIX but not valid integer appended to them.
//NOthing to do
}
}
}
return maxFileNumber;
}
private static boolean incrementFileNumber(final int oldNumber) {
File oldfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + oldNumber);
File newfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + (oldNumber + 1) + ".txt");
return oldfile.renameTo(newfile);
}
}
public static void main (String[] args) throws Exception
{
File foldersContainer = new File("c:/test");
String latestFileName = "";
Integer highestFileNumber = 0;
for (File tmpFile : foldersContainer.listFiles()){
if (tmpFile.isFolder()) {
int currentNumber = extractFileNumber(tmpFile.getName());
if (currentNumber > highestFileNumber){
highestFileNumber = currentNumber;
latestFileName = tmpFile.getName();
}
}
}
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
System.out.println("Latest file (incremented): " + latestFileName);
}
private static int extractFileNumber(String name){
for (int x=name.length()-1; x >= 0; x--)
if (!Character.isDigit(name.charAt(x)))
return Integer.parseInt(name.substring(x+1));
return -1;
}
If the filename before the last number can contain numbers, then you should use lastIndexOf to be sure of finding only the occurrence you really want to increment.
instead of
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
you should use
latestFileName = latestFileName
.substring(0,latestFileName.lastIndexOf(highestFileNumber.toString()))
.concat((++highestFileNumber).toString());
Ok, here's an alternative. I'm assuming that the file name is known and they have the same name.
public static void main(String[] args) {
File dir = new File("directory of the files");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("folder");
}
});
for (File file : files) {
System.out.println(file.getName());
}
System.out.println("---------");
List<File> myFile = new ArrayList<>(Arrays.asList(files));
Collections.sort(myFile, new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
// TODO Auto-generated method stub
int numberF1 = Integer.parseInt(f1.getName().replace("folder",""));
int numberF2 = Integer.parseInt(f2.getName().replace("folder",""));
return Integer.compare(numberF1, numberF2);
}
});
for (File file : myFile) {
System.out.println(file.getName());
}
}
Output :
folder10
folder2
folder20
folder250
---------
folder2
folder10
folder20
folder250

Categories