0

I want to read a file and its directory using scanner. The problem is the directory is not read through scanner because there is a white space in it. I tried to handle it with S.nextLine() but it doesn't skip execution and skip to the rest of the code. This is the code:

public class readFile {

   public static void main (String args[]){
    System.out.print("Enter test file directory: ");
    testFile = S.nextLine();
    //testFile = "C:\\Users\\firstname lastname\\Desktop\\test1.txt"; This works 
    File test = new File(testFile);
    try
    {
      Scanner readFile = new Scanner(test);

      while(readFile.hasNextLine())
     {
        int i = readFile.nextInt();
        System.out.println(i);
     }
     readFile.close();
     }catch(FileNotFoundException e){System.out.println("File doesn't exist");}
   }
}  
onlyforthis
  • 404
  • 5
  • 19
  • What does it print if you write `System.out.println(testFile);`? – Tom Dec 02 '14 at 15:32
  • C:\\Users\\firstname – onlyforthis Dec 02 '14 at 15:34
  • 1
    Are you sure the file exists cause this code works fine for me...make sure you declare `String testFile;` I don't see it declared anywhere also `Scanner S = new Scanner(System.in);`. – brso05 Dec 02 '14 at 15:38
  • Ah I see a cause of a problem: You've edited your username to `firstname lastname` for the constant version. `Scanner#next()` reads everything until the next whitespace. Therefore it doesn't read the whole line if you have a whitespace in your path. Use `nextLine()` instead. – Tom Dec 02 '14 at 15:40
  • I realized that the problem is i have a space in my username. so I need to know how to handle the space in the directory? Thank you – onlyforthis Dec 02 '14 at 15:41
  • @Tom Yeah i knew its the white space, but `nextLine` doesn't work. it doesn't wait for my typing and skip to the rest of the code emmediately – onlyforthis Dec 02 '14 at 15:46
  • Can you update your code, please? – Tom Dec 02 '14 at 15:47
  • If this code is used in a project with more input requests to the user, then keep in mind, that you can't directly call `nextLine()` if you used `nextInt()` or `nextDouble` or something like that before that call. – Tom Dec 02 '14 at 15:51
  • @Tom I see. So what to do? should i create another scanner for `nextLine()` ? – onlyforthis Dec 02 '14 at 15:52
  • No not necessary, [read this question and its answers](http://stackoverflow.com/questions/13102045/skipping-nextline-after-use-nextint) for a solution. – Tom Dec 02 '14 at 15:53
  • 1
    @Tom it worked. Thank you very much. – onlyforthis Dec 02 '14 at 15:56

0 Answers0