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
Related
I'm required to take a file name as input for a scanner in one method and use that scanner as reference to the file path for the rest of my code in all other methods.
I'm learning file i/o, and for this project I'm supposed to take a file name as input, count the number of lines in the file and put each line into an array.
My issue comes in during the FileUtils.countRecords method. After returning a file type in FileUtils.openInputFile and then taking that data and putting it into a scanner (variables inf and fin in the code) I'm supposed to take that scanner and use it to point to a file again. (File input=new File(scanner))
*My instructor gave us a hint that "The Scanner is at the EOF and will need to be reset" though I haven't been able to find any 'end of file' documentation that would help me here.
From main method (!this can not be changed!)
File inf = null;
int total, choice;
String [] words = null;
Scanner kb = new Scanner(System.in), fin = null;
inf = FileUtils.openInputFile(kb);
fin = new Scanner(inf);
total = FileUtils.countRecords(fin, 1);
fin.close();
FileUtils.openInputFile(kb) returns the type File after being given the file's path.
public static int countRecords(java.util.Scanner fin,int linesPer)
{
File input = new File(fin.toString()); //fileNotFoundException here
File input = new File(fin); //also throws filenotfoundexception
When I try System.out.print(fin) or System.out.print(fin.toString()) I get this:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E]
Which is obviously not a file name or path. I'm wondering if I need to convert my scanner into something else before assigning my file variable to it. Or if there is something like .toString() that would turn the above scanner properties into readable text. Or how to "reset the scanner at the eof."
So I guess the scanner fin doesn't hold the path/file name. It is a reference to the open file itself, therefore all I needed to do was count each line from the file like so:
while(fin.hasNext())
{
fin.nextLine();
count ++;
}
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));
Using java, I need to make a program that asks the user which file to scan, and to do some work with the data in the file.
My program is supposed to select a file, scan the file for a specific character that the user specifies, and return with how many specific characters there are in that file.
This is my code so far:
import java.io.*;
import java.util.Scanner;
public class CharSearch {
public static void main(String[] args) throws Exception{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the file you want to search.");
String fileInput = scanner.nextLine();
System.out.println("What character would you like to look for in " + fileInput + "?");
Scanner fileScanner = new Scanner(fileInput);
System.out.println(fileScanner);
}
}
I imported io and scanner, then set up the scanner to read which file the user inputs. I print back out that file name. The last two lines are where I need help. How can I make the scanner return with the data in the file.
There is a file in my folder called data.txt and all that is written in it is "dataWord." For starters, I want the scanner to read the file and the program to display dataWord, but its not working. I am a rookie, so please work with me. Thanks.
Instead of passing path of file as String pass it as a File
Scanner fileScanner = new Scanner(new File(fileInput));
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
scanner.close();
fileScanner.close();
If the file is an external file or not in your project, you can specify the absolute path of file.
If it is in classpath you can read using ClassLoader
java.io.InputStream inputStream = this.getClassLoader().getResourceAsStream("file_path")
Scanner has a constructor with InputStream
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.
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();
}