Using the same Scanner in java - java

Can I use the Scanner to read from the user to enter a certain input, and then, create a new instance of it to read from a file for example?
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(fileName);
displayAll(sc); //a static void method that takes the Scanner object as a parameter and is supposed to read and display the input stored in the .txt file

Well, you need to use a File:
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(new File(fileName));
It would be safer to try-catch not-existing file. You can use if-else. Well... logic is up to you. Maybe something like that:
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter file name");
String filename = sc.next();
if (!filename.startsWith("sth")) { //this will reask if the file name doesn't start with "sth"
continue;
try {
Scanner s = sc; //just in case you never gonna use System.in
sc = new Scanner(new File(filename));
s.close(); //just in case you're sure you never gonna use System.in
break;
} catch (Exception e) {
System.out.println("Wrong filename - try again");
}
}
Obviously, you can change the if condition to whatever you like. I just wanted to give you a wider perspective. You can switch to equals if you wish ofc.

You are not using the same Scanner as stated in your question title. You are creating two different and independent instances of Scanner.
sc in your code is a Scanner reference. At first, it references the first Scanner object. Then you change the object reference to point to the second Scanner object. You are not reusing the Scanner objects, you are reusing the object reference. This is perfectly OK.
When a Scanner object is created, the source used by the scanner can't be changed. Get data from a different source requires a new instance to be created.
In your code example, your approach to use two different scanner for System.in and a file is good. However, the issue in your example is that you are using the wrong constructor for the file Scanner. To create a Scanner using the file as the source, you need to create a File or Path object and use this object as the constructor parameter instead of the filename String:
new Scanner(new File(filename));
Or:
new Scanner(Paths.get(filename));

Related

Using a Scanner to solicit a file name JAVA

I am trying to open whose name is written into the console. I can't seem to resolve the type mismatch. Any help would be appreciated.
Scanner inputFileName = new Scanner(System.in);
File file = new File (inputFileName);
Use something like this: String name = inputFileName.nextLine(). So when you call nextLine() you are reading the rest of this first line.
In your code, you are not getting any input from the user.
You'll find more information on their implementation in the API Documentation for java.util.Scanner
In your case, your inputFileName is only a Scanner object which you can use it to prompt for user input. It is not your filename nor is it prompting for any input at the moment.
You may use inputFileName.nextLine() to prompt user for input first:
Scanner inputFileName = new Scanner(System.in); //Create Scanner object
String fileName = inputFileName.nextLine(); //Store user's input in fileName
File file = new File (fileName); //Create File object with fileName

Pathway issue java

I have a piece of code I'm currently struggling with
System.out.println("What file would you like to open?");
Scanner sc = new Scanner(System.in);
String files = sc.nextLine();
Scanner input = new Scanner(new File(files));
Basically, let's say I have a file called text.txt and I enter that as user input for the scanner to analyze, where should it be placed in my directory? I tried to put it in the bin and src files of my class and inside my class also but I keep getting a FileNotFoundException at the line:
Scanner input = new Scanner(new File(files));
It doesn't even ask me for any user input.
With
String current = System.getProperty("user.dir");
you can check where you are currently in.
You might try just putting it in the project root folder, one above src/bin.

readfile in from text file elements java

I'm trying to read in a .txt file in but when i use debugger it gets stuck on nextline? Is there some logic error that im doing? It's all being stored into an array through multiple objects:
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
System.out.println("Enter your file name");
String name = "";
kb.nextLine();
name = kb.nextLine();
File file = new File(name);
return file;
}
The scanner I passed into it is:
Scanner fin = null, kb = new Scanner(System.in);
File inf = null;
inf = FileUtil.readFileInfo(kb);
fin = new Scanner(inf);
You're reading from two different "files" here:
System.in, the standard input (or "terminal"), which you're using to ask the user for a filename
the file with the name you get from the user
When you call name = kb.nextLine();, you're asking the parameter (the Scanner built with System.in) for its next line. Generally, that will actually block ("hang") until it receives another line of input (the filename) from the user. If running from a command line, enter your text into that window; if running in an IDE, switch to the Console tab and enter it there.
As quazzieclodo noted above, you probably only need to call readLine once.
After that, you can open up your second Scanner based on the File that readFileInfo returns, and then you're actually reading from a text file as expected.
Assuming that your intention is to use Scanner to read a text file:
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Repeat use of Scanner.hasNextLine()

During one of my assignment i was trying to read a file and print it line by line. I tried to use the hasNextLine again and it didn't work. I tried to complete it somehow but i want to know if there is some way i can go through my file all again without creating a new Scanner.
here is my code snippet
sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
I want to use the while again later but i cant do that. Is there a way to reset or bring it back to the top and traverse through the file again.
You can just create a new Scanner after closing the first one:
sc.close();
sc = new Scanner(new File(args[0]));
// do the same thing again
To optimize, you can save reference to file for future use.
File f = new File(args[0]);
sc = new Scanner(f);
//...
sc = new Scanner(f);
Scanner is anything but smart iterator, so cost of creating new can be smaller than 'rewinding' old one.
You can use a FileReader decorating a RandomAccessFile:
RandomAccessFile f = new RandomAccessFile(args[0], "r");
Scanner sc = new Scanner(new FileReader(f.getFD()));
//Read through scanner
//Rewind file
f.seek(0L);
//Read through file again

Finding and replacing words in a text file with Scanner and Printwriter classes

I'm currently attempting to write a program that can scan a text document and replace a specified word / string / whatever with another phrase, specifically using the classes Scanner and Printwriter. Unfortunately, I'm having a little bit of trouble finding the correct methods to use and how exactly to implement them. Here's my code:
class Redaction {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out
.println("Please enter the filename of the sensitive information");
String f = input.next();
System.out.println("Please input what text you want 'lost'");
String o = input.next();
System.out
.println("Please input what you want the new, improved filename to be called");
String n = input.next();
File sensitiveDocument = new File(f);
if (!sensitiveDocument.exists()) {
System.out.println("File does not exist.");
System.exit(0);
}
Scanner in = new Scanner(sensitiveDocument);
in.useDelimiter("[^A-Za-z]+");
PrintWriter out = new PrintWriter(n);
while (in.hasNext()) {
if (in.hasNext(o)) {
// ...
}
}
in.close();
out.close();
}
}
I'm pretty lost at this point. Any help would be much appreciated.
Start by reading PrintWriter and Scanner documentation, to decide which methods to use.
Pseodo code:
Get line by line (or word by word, depends on what you want to remove).
look for the string you want to remove
if the string contains the content to remove, remove it.
print the string to the file.
The simplest although not so efficient algorithm would be to read the contents of the file into a string variable. After which you could use a String Tokenizer to find and replace the word you don't want with the word you want and rewriting the contents of the variable back into the file.

Categories

Resources