Reputation: 1476
I know there are already similar questions here but i tried the solutions but none worked,so i providing my code and java build path configurations settings ,so kindly help.i am using java 1.8
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Pics {
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null.
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
}
I am attaching the snapshot of the error,even though the curly braces are balanced but it still show error to insert "}" to complete class body
Upvotes: 3
Views: 1187
Reputation: 311
In Java, only the declarations of variables can be written directly in class but in case you want to write some logic, use the functions. This is what the definition of class says: wrapper for data and functions that act on that data. Additionally use constructors to provide wrapper to initializations.
import java.io.File;
import java.util.ArrayList;
import java.utilList;
public class Pics {
List<String> results;
File[] files = null;
public Pics() {
results = new ArrayList<String>();
files = new File("/path/to/the/directory").listFiles();
}
//If this pathname does not denote a directory, then listFiles() returns null.
public void testFunction() {
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
}
}
Upvotes: 1
Reputation: 393781
This for loop must be inside some method :
for (File file : files) {
if (file.isFile()) {
results.add(file.getName());
}
}
Upvotes: 1