Fixing Syntax Issues with Java File Inputs

  • Context: Java 
  • Thread starter Thread starter TMM
  • Start date Start date
  • Tags Tags
    File Issues Java
Click For Summary
SUMMARY

The discussion focuses on resolving syntax issues related to file input in Java using the scanner class from the java.util package. The user initially encountered problems with passing a filename that requires quotes, which led to confusion between string literals and variable references. The solution provided involves concatenating quotes around the input string when creating the File object, allowing for successful file reading. The final working code snippet demonstrates the correct implementation of the Scanner and File classes.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with the java.util.Scanner class
  • Knowledge of the java.io.File class
  • Basic concepts of string manipulation in Java
NEXT STEPS
  • Explore Java exception handling for file operations
  • Learn about Java I/O streams for advanced file handling
  • Investigate the use of BufferedReader for efficient file reading
  • Study Java regular expressions for advanced search functionalities
USEFUL FOR

Java developers, software engineers, and students learning file handling and input processing in Java.

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.
 
Technology 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:

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 28 ·
Replies
28
Views
4K
  • · Replies 1 ·
Replies
1
Views
7K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
4K