简体   繁体   中英

How to access directory with full file path?

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.

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, eg this would have led you to a solution quickly:

System.out.println("input was " + input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM