Reputation: 65
So, I'm writing a program that needs to iterate through all files in a directory and here is what I currently have.
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String args[]) throws Exception {
VotingData v = new VotingData();
Scanner in = new Scanner(System.in);
System.out.print("Please input a directory.");
String input = in.next();
File dir = new File(input);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
v.merge(RecordReader.readRecord(child.toString()));
}
}
else {
// do nothing right now.
}
String[] sub1 = {"Montgomery","Miami"};
TextualRepresentation.toString(v.getAllResults());
TextualRepresentation.toString(v.getCountyResults("Montgomery"));
TextualRepresentation.toString(v.getCountyResults("Miami"));
TextualRepresentation.toString(v.getCountyResults("Butler"));
TextualRepresentation.toString(v.getSubsetResults(sub1));
}
}
The filepath of the project is C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff.
The input I'm trying is "C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles" , but it doesn't seem to work. However, when input is just "TestFiles" it does. I want to be able to access directories in different folders, but for some reason the long method isn't working.
Edit: I don't know what the error is. All I know is when I put "TestFiles" into the Scanner it works fine and when I try the full file path it doesn't crash, but it doesn't yield the results I want.
Upvotes: 0
Views: 538
Reputation: 40325
Scanner#next()
reads white-space delimited (by default) string tokens.
Your input:
C:\Users\Jarrett Willoughby\Documents\School\CSE201\Project Stuff\TestFiles
Contains spaces, so next()
just reads "C:\Users\Jarrett".
You can use Scanner#nextLine()
instead.
In the future, to debug on your own, either step through in a debugger to see what values variables have, or add print-outs to verify, e.g. this would have led you to a solution quickly:
System.out.println("input was " + input);
Upvotes: 1