Reputation: 113
This condition reads all the files:- if(listOfFiles[i].isFile())
and this else if(listOfFiles[i].isDirectory())
condition tells whether there is any sub folder.
If there is a subfolder, then I again called the same method. i.e: ft.fileChecker(s2);
But at this step it throws a run-time error.
//Main class
public class FileCounter {
public static void main(String[] args) {
String s = "C:\\Users\\Nitk\\Desktop\\Project";
FileTester ftMain = new FileTester();
ftMain.fileChecker(s);
}}
//----------
import java.io.*;
import java.util.*;
public class FileTester {
FileTester ft = new FileTester();
public void fileChecker(String folderPath) {
File f = new File(folderPath);
File[] listOfFiles = f.listFiles();
List<String> list = new ArrayList<>();
FileLineCounter flc = new FileLineCounter();
int count = 0;
boolean isFound; boolean isFoundTxt;
String s = null;
for(int i =0; i < listOfFiles.length; i++){
if(listOfFiles[i].isFile()){
System.out.println(i +". File:" + listOfFiles[i].getName());
s = listOfFiles[i].getName();
list.add(s);
}else if(listOfFiles[i].isDirectory()) {
System.out.println(i +". Directory: " + listOfFiles[i].getName());
String s2 = folderPath+"\\"+listOfFiles[i];
ft.fileChecker(s2);
}
}
}
}
Output:
--------
Run-time error:
Exception in thread "main" java.lang.StackOverflowError
at FileTester.<init>(FileTester.java:3)
at FileTester.<init>(FileTester.java:4)
...
at FileTester.<init>(FileTester.java:4)
at FileTester.<init>(FileTester.java:4)
C:\Users\Nitish\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
Upvotes: 0
Views: 536
Reputation: 88
Your code has 2 flaws.
FileTester ft = new FileTester();
inside FileTester Class,
instead just use fileChecker()
.String s2 = folderPath+"\\"+listOfFiles[i].getName(); fileChecker(s2);
Upvotes: 0
Reputation: 896
When you invoke the constructor of class FileTester
, the field ft
is initialized. Since ft
is of type FileTester
, initializing said field means invoking the constructor of class FileTester
again which initializes the ft
field which invokes the constructor which initializes the ft
field which invokes the constructor ...
In short, removed the line FileTester ft = new FileTester();
from class FileTester
.
Upvotes: 3