Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Scanner

  1. Oct 26, 2007 #1


    User Avatar

    So I made a program that finds files and searches in them for key terms using the scanner class in java.util.*;

    I've written it something like this:
    Scanner filereader = new Scanner(System.in);
    String filename = filereader.nextLine();
    Scanner searcher = new Scanner(new File(filename));

    The problem is with the filename argument. I need quotes around it to fix the syntax, but even when my input contains quotes it doesn't quite work, and when I add them in the program itself they turn my variable, filename, into a string literal. Is there a way to get around this (some type of escape code perhaps?) or a different method altogether? Any help is much appreciated.
  2. jcsd
  3. Oct 26, 2007 #2


    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    If you do this:

    String filename = "file.dat";
    File f = File(filename);

    then you have created a string literal, stored it in a variable, and passed it to the constructor of File. You can also create a File object by passing it a string literal directly, like this:


    - Warren
  4. Oct 26, 2007 #3


    User Avatar

    Ah I see. Thanks. :D

    I got it working with:
    Scanner filename = new Scanner(System.in);
    String s = filename.nextLine();
    File f = new File('"' + s + '"');
    Scanner reader = new Scanner(f);
    Last edited: Oct 26, 2007
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Java Scanner
  1. Pointer, scanner help (Replies: 16)

  2. JAVA GridLayout (Replies: 1)

  3. Java interpreter (Replies: 8)

  4. Java Cylinders (Replies: 2)