The program must print the text in file I ask it to read.
The problem is I coded it to read the text from a specific file
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
How do I get the program to read the text from a file specified by user input?
*The file is going to be in the same directory/folder as the program so that's not an issue.
EDIT: My prior attempt at user input
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Declare a String variable, such as someUserFile, take user input. Then...
File file = new File(someUserFile);
Scanner inputFile = new Scanner(file);
You may want to check their input and append ".txt" to the end of their input.
If this works:
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Then this:
Scanner keyboard = new Scanner(System.in);
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
Will do the exact same thing assuming you type numbersonnumbers.txt and type that exactly.
Assuming you type numbersonnumbers.txt exactly, the second snippet does the EXACT same thing as the first snippet.
Firstly you should ask the user the input the filename. Then just replace the "numbersonnumbers.txt" in your code to the variable that you set for the user input.
Scanner in = new Scanner(System.in);
System.out.println("What is the filename?");
String input = in.nextLine();
File file = new File(input);
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
File file = new File(fileName);
Scanner inputFile = new Scanner(file);
1) The program must print the text in file:
Lets call this file, dataFile.text, or dataFile.dat (either way works)
Assuming that the client will be inputing any file, we must get the file's name...
These Java statements will do the trick:
// Create a Scanner to read user's file name
Scanner userInput = new Scanner(System.in);
// Request the file name from client
System.out.println("Enter name of input file: ");
// Gets client's file name
String fileName = scanFile.nextLine();
// scanFile, scans the new File fileName (client's file), which is located in the src directory. The "src/" represents the path to the file (client's file).
Scanner scanFile = new Scanner(new File("src/" + fileName));
Since the problem states the file, "will be located in the same directory as the program," its not an issue.
---------------------------------------------------------------------------------
2) The problem is I coded it to read the text from a specific file
Yes, all you did was create file of your own called, "numbersonnumbers.txt," this is exactly the code you should be following in the solution to this problem, but instead of typing "numbersonnumbers.text", you will be using the client's input file, which is the String variable "fileName" in the previous code...*
File file = new File("numbersonnumbers.txt");
Scanner inputFile = new Scanner(file);
Corrected: File file = new File("src/" + fileName);
Scanner inputFile = new Scanner(file); // Will scan all the file's data
Corrected More: Scanner inputFile = new Scanner(new File("src/" + fileName));
---------------------------------------------------------------------------------
3) The program must print the text in file
Now to print the data items in the file to the console you simply, copy every item in the file, to an array, list, or tree depending on specifications of implementation, but this is obviously begininer programming so, never mind lists and trees, use an array.
So you have completed upto either Scanner scanFile in #1 or Scanner inputFile in #2
Now, create an array, obviously the type of array would be based on the type of data items in the file... Strings for (e.g., month names) or int for (e.g., ID numbers .. ect)
Assuming the data items in the file are names of months (jan, feb, march) we will make an array of type String.
String[] fileData = new String[100]; // has random length (100)
// Now we will be copying every item from the file into the array, you will need place holder value to keep track of the position during the traversal (stopping at every item) of the file's items.
int i = 0; // itialize the start of the traversal (index 0 of the file items)
while (scanFile.hasNextLine()) { // While file has input on next line, read from file.
fileData[++i] = scanFile.nextLine(); // Input file data and increment i
System.out.println(fileData[i]); // Prints all of the file's data items
} // end while
Respectfully,
-!di0m
You got almost everything you need in your code already. You just need to re-arrange your lines of code properly, and add couple more.
you need two steps: scan what the user enters as full file path, then scan the actual file data as follows:
// Scanner Object to be used for the user file path input
Scanner keyboard = new Scanner(System.in);
// Asks the user to enter the full path of their file
System.out.print("Enter your full file path: ");
// Stores the user input file path as a string
String filename = keyboard.nextLine();
// Creates a File object for the file path, and scans it
Scanner inputFile = new Scanner(new File(filename);
Now you can read the scanned File inputFile. For example you can use a while loop to read one line at a time to read all data and print it out as follows:
// Reads one line at a time, and prints it out
while(inputFile.hasNext) {
System.out.println(inputFile.nextLine());
Or you can put each line's raw data (trimmed and split) in an array and print out each line as an array as follows:
// Declares a String array[] to be used for each line
String[] rawData;
// Reads one line at a time, trims and split the raw data,
// and fills up the array with raw data elements, then prints
// out the array. it repeats the same thing for each line.
while (scanner2.hasNext()) {
rawData = scanner2.nextLine().trim().split("\\s+");
System.out.println(Arrays.toString(rawData));
}
Related
I'm trying to get my program to read data from a text file and store it in an array. The text file contains data about a planet.
Here is an example:
Mercury
4.151002e10
2.642029e10
-1.714167e9
-3.518882e4
4.355473e4
6.785804e3
3.302e23
My file is named test.txt. It lives in the same directory as my class.java file. I've used System.out.println(new File("test.txt").getAbsolutePath()); to check if the directory path is correct, which it was, and I used System.out.println(new File(".")); to check if it was in the same directory that the code was trying to compile in, which again it was (outputted just a dot which I was led to believe meant it was in the correct directory). I've tried different ways of finding the file, such as renaming it to something else to check it wasn't a keyword, changing the encoding of the file to Unicode, or UTF-8, or ANSI, none of which worked, using .\test in the file to look in the same directory, none of which worked.
Here is my code:
public static void defaultPlanetArray(){
Planet[] solarSystem;
solarSystem = new Planet[9];
PhysicsVector dummyAcceleration = new PhysicsVector();
System.out.println(new File("test.txt").getAbsolutePath());
System.out.println(new File("."));
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
}
catch(FileNotFoundException e){
System.out.println("File not found!");
}
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
PhysicsVector and Planet are both classes I have created. PhysicsVector and the rest of Planet apart from this excerpt compile with no problems. When I try to compile this specific bit of code, I get:
.\Planet.java:65: error: cannot find symbol
while(i<9 && scnr.hasNextLine()){
^
I'm guessing this means that the variable scnr is not being created in the try section because it cannot find the file. I think this because when I don't include the try and catch blocks, I get:
.\Planet.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
Scanner scnr = new Scanner(file);
^
I've also tried the catches FileNotFoundException when I'm first creating the method but that gives me the same error as immediately above.
I could just set the values in the program, but that would give a lot of unnecessary code and be rather inefficient I think.
So my question is, how do I get the scanner to read my values from the file?
As #Lalit Verma pointed the scnr variable you defined lives inside the try - catch block.
Change the code to:
try{
File file = new File("C:\\Users\\Lizi\\Documents\\Uni Work\\Year 2\\PHYS281\\Project\\test.txt");
Scanner scnr = new Scanner(file);
int i = 0;
while(i<9 && scnr.hasNextLine()){
//read values from file and set as Planet object, then set to array.
i++
}
}catch(FileNotFoundException e){
System.out.println("File not found!");
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
I'm working on a program that allows the user to specify one of three functions via keyboard input. Each of the functions works properly except for one. When it exits back to the initial prompt it outputs the prompt to the console twice.
Here's the opening prompt:
"Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit"
When I run any of the listed functions (barring exit) they execute normally and return to the opening prompt. The search function however prints the opening prompt twice to the console instead of once.
This is the code for the Opening:
public static void main(String args[]) throws IOException{
//Initialize scanner and a string variable to hold the value of scanner variable
Scanner inputChoice = new Scanner(System.in); //iChoice - inputChoice
while(!inputChoice.equals("e")){
//Prompt user to provide input in accordance with desired function
System.out.println("Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit");
String userChoice = inputChoice.nextLine();
//If user specifies "r" go to fileReader class
if(userChoice.equalsIgnoreCase("r")){
SimpleDBReader sdbrObject = new SimpleDBReader();
sdbrObject.sdbReader();
//If user specifies "s" go to textSearch class
}else if(userChoice.equalsIgnoreCase("s")){
SimpleDBSearch sdbsObject = new SimpleDBSearch();
sdbsObject.sdbSearch(inputChoice);
//If user specifies "w" go to fileWriter class
}else if(userChoice.equalsIgnoreCase("w")){
SimpleDBWriter sdbwObject = new SimpleDBWriter();
sdbwObject.sdbWriter(inputChoice);
//If user specifies "e" terminate program
}else if(userChoice.equalsIgnoreCase("e")){
inputChoice.close();
System.exit(0);
}
}
}
This is the code for the Search:
public void sdbSearch(Scanner searchWord) throws IOException{
//Prompt user for input
System.out.println("Please input the word you wish to find:");
//Init string var containing user input
String wordInput = searchWord.next();
//Specify file to search & init Scanner containing file
File file = new File("C:/Users/Joshua/Desktop/jOutFiles/SimpleDb.txt");
Scanner fileScanner = new Scanner(file);
//Set flag - for below loop - to false
boolean stringFound = false;
//Loops through every line looking for lines containing previously specified string.
while(fileScanner.hasNextLine()){
String line = fileScanner.nextLine();
if(line.contains(wordInput)){ //If desired string is found set flag true and print line containing it to console
stringFound = true;
System.out.println("I found the word you're looking for here: " + line);
}
}
//Check if flag false, prompt user for new input
if(!stringFound){
System.out.println("The word you were looking for does not exist.");
}
}
The interaction and output I expect is:
Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit //SysOut
s //User
Please input the word you wish to find: //SysOut
someString //User
I found the word you're looking for here: lineWithString OR The word you were looking for does not exist. //SysOut
Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit //SysOut
What I get is:
Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit //SysOut
s //User
Please input the word you wish to find: //SysOut
someString //User
I found the word you're looking for here: lineWithString OR The word you were looking for does not exist. //SysOut
Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit //SysOut
Type 'R/r' to read a file; 'S/s' to search for text within a file; 'W/w' to write to a file; 'E/e' to exit //SysOut
Call to scanner.next() leaves behind a newline character which is then read in call to scanner.nextLine(). Add a scanner.nextLine() after searchWord.next(); or better change searchWord.next(); to searchWord.nextLine();
So I'm trying to read a file using the Scanner, however, all the contents of the file are wiped, and then it reads nothing. Here are the methods I've ran in succession, in my Main method:
private static Scanner x;
private static Formatter y;
public void openMainFile(String name){
try{
x = new Scanner(new File("main.mcmm");
y = new Formatter("main.mcmm");
}catch(Exception e){
GUI.error(2);
}
}
This method runs perfectly fine
public void readModMainFile(){
while(x.hasNext()){
Main.name = x.next();
Main.ver = x.nextFloat();
Main.base = x.nextBoolean();
Main.dev = x.next();
Main.date = x.next();
}
}
After this method runs, the file is empty, and the 'Main.-' variables don't have any values.
Don't open the same file for reading and writing at the same time. Write into a temporary file first, then rename it. Alternatively, you can read the whole file first, store everything, close the Scanner and then you can overwrite the file.
Your Formatter is truncating the output file every time. From your comments in this post, you indicate that the number of variables will remain constant. You could use a temporary file to achieve this (+1 to #biziclop):
File inputFile = new File("main.mcmm");
Scanner scanner = new Scanner(inputFile);
File tempFile = File.createTempFile("main.mcmm",".temp");
Formatter y = new Formatter(tempFile);
y.format("%s", name);
// more reading & formatting, etc.
y.close();
scanner.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Remember to close both the Scanner and Formatter so that the input & output files can be deleted & renamed respectively.
I have a folder which file name is: "List of names". Inside that folder i have a 5 ".txt" file documents and each document file names is a person's name.
I want to retrieve the five documents and display the strings inside each documents. How do i do this? I tried this:
import java.io.*;
import java.util.*;
public class Liarliar {
public static void main(String args[])throws IOException{
File Galileo = new File("C:\\List of names\\Galileo.txt");
File Leonardo = new File("C:\\List of names\\Leonardo.txt");
File Rafael = new File("C:\\List of names\\Rafael.txt");
File Donatello = new File("C:\\List of names\\Donatello.txt");
File Michael = new File("C:\\List of names\\Michael.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
try{
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
}catch(FileNotFoundException e){
}catch(IOException e){
}
}
}
Thanks in advance for someones time...
It would be more generic to not hard code the names of the individual files like Galileo.txt. You can create a File representing the directory, and then call listFiles to get all the files in the directory, like
File nameFile = new File(""C:\\List of names");
File[] personFiles = nameFile.listFiles();
Then you can iterate over this File array, and open each file in turn, and read the contents, like
for (File person : personFiles) {
showFileDetails(person);
}
where showFileDetails is a separate method you write for opening the file and displaying the information.
the following lines are not needed as they are meant to take input from user.
System.out.println("Enter a number list of names:");
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
Instead you need to read the files one by one using a FileInputStream or FileReader. See here for an example on how to read data from files. Do this for each of your files.
I need to retrieve and change a number in a text file that will be in the first line. It will change lengths such as "4", "120", "78" to represent the data entries held in the text file.
If you need to change the length of the first line then you are going to have to read the entire file and write it again. I'd recommend writing to a new file first and then renaming the file once you are sure it is written correctly to avoid data loss if the program crashes halfway through the operation.
This will read from MyTextFile.txt and grab the first number change it and then write that new number and the rest of the file into a temporary file. Then it will delete the original file and rename the temporary file to the original file's name (aka MyTextFile.txt in this example). I wasn't sure exactly what that number should change to so I arbitrarily made it 42. If you explain what data entries the file contains I could help you more. Hopefully this will help you some anyways.
import java.util.Scanner;
import java.io.*;
public class ModifyFile {
public static void main(String args[]) throws Exception {
File input = new File("MyTextFile.txt");
File temp = new File("temp.txt");
Scanner sc = new Scanner(input); //Reads from input
PrintWriter pw = new PrintWriter(temp); //Writes to temp file
//Grab and change the int
int i = sc.nextInt();
i = 42;
//Print the int and the rest of the orginal file into the temp
pw.print(i);
while(sc.hasNextLine())
pw.println(sc.nextLine());
sc.close();
pw.close();
//Delete orginal file and rename the temp to the orginal file name
input.delete();
temp.renameTo(input);
}
}