Fixing Syntax Issues with Java File Inputs

  • Context: Java 
  • Thread starter Thread starter TMM
  • Start date Start date
  • Tags Tags
    File Issues Java
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 10K views
TMM
Messages
92
Reaction score
0
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.
 
Physics news on Phys.org
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:

File("file.dat")

- Warren
 
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: