Even though the file Movie_db.txt isn't empty, I get the following exception:
the text file consists of this:
hank horror 20.0 18 1
public void syncDB(List<Movie> movieList) throws IOException {
Scanner scanner = new Scanner("Movie_db.txt");
BufferedReader reader = null;
try {
String line = null;
String title;
String genre;
double movieDuration;
int ageRestriction;
int id;
while (scanner.hasNext()) {
title = scanner.next();
genre = scanner.next();
movieDuration = scanner.nextDouble();
ageRestriction = scanner.nextInt();
id = scanner.nextInt();
movieList.add(new Movie(title, genre, movieDuration, ageRestriction, id));
}
} catch (Exception e) {
System.out.println("List is empty");
}
}
Considering your path is correct, there is a problem in your code. I'd change this line
Scanner scan = new Scanner("Movie_db.txt");
with this one
Scanner scan = new Scanner(Paths.get("Movie_db.txt"));
The reason is that in your snippet the Scanner only reads the string "Movie_db.txt" and in the second snippet it recognizes as the path to file.
Read Scanner documentation for more info
genre = scan.next(); line is throwing exception because nothing is left to read from file now, which causes catch block to execute.
You are providing a string to Scanner which is a valid input for scanner. Hence, it never reads the file.
Scanner scan = new Scanner(new File("full_path_to_container_dir/Movie_db.txt"));
Please have a look at this blog on how to read from a file using scanner - https://www.java67.com/2012/11/how-to-read-file-in-java-using-scanner-example.html.
Related
I have a txt file of names and genders that I imported for this java program. The scanners are supposed take a user input (name and gender) and compare it line by line to find it within the text file and then print the line at which the name was found. However, only some names work and not others. I think it may be because the program only reads every other line but im not sure if thats the problem, or how to fix it.
Link to the name file: http://courses.cs.washington.edu/courses/cse142/16au/homework/names.txt
public static void fileSearch() throws FileNotFoundException {
System.out.println("What name are you looking for?");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
String gender = scan.nextLine();
File file = new File("names.txt");
Scanner fileScan = new Scanner(file);
while (fileScan.hasNextLine()) {
String line = fileScan.nextLine();
Scanner lineScan = new Scanner(line);
String nameText = lineScan.next();
String genderText = lineScan.next();
if (name.equalsIgnoreCase(nameText) && gender.equalsIgnoreCase(genderText)) {
System.out.println(line);
}
}
}
}
Program compiles and runs perfectly until I try to execute my load method in main. Program crashes and gives me an input mismatch exception at
part number = scan.nextInt(); ..... Anyone know why?
public static InventoryManager load(String fileName) throws IOException,ClassNotFoundException
{
Scanner fileScan = new Scanner (new File(fileName));
Scanner stringScan;
InventoryManager StockChart = new InventoryManager();
// Part variables
String record = "";
int partNumber=0;
String description="";
int qty=0;
double cost = 0.00;
while(fileScan.hasNext())
{
record = fileScan.nextLine();
stringScan = new Scanner (record);
stringScan.useDelimiter(" "); //allows for separation when reading
partNumber = stringScan.nextInt(); // scans part number
description = stringScan.next(); // scans description
qty = stringScan.nextInt(); // scans the qty on hand
cost = stringScan.nextDouble(); // scans the item cost
//create new part object for each line in file
StockChart.addStock(new Stock(partNumber,description, qty,cost));
}
return StockChart; // return new list back to InventoryClerk program
}
Text File is formatted as follows (disregard spaces in between):
1117[tab]1/2-13 FHN[tab]450[tab]6.11
1118[tab]1/2-13 FHN[tab]100[tab]0.23
1119[tab]1/2-13 FHN[tab]100[tab]4.11
A better way rather than using the stringScan Scanner object is to simply to use String.split on the record String
e.g.
while(fileScan.hasNext())
{
record = fileScan.nextLine();
String el[] = record.split (" ");
partNumber = Integer.parseInt (el[0]);
description = el[1];
// etc
Im trying to write a program that will ask for the name of an input file and an output file. It will open the input file and create the output file. It will then read the input file and make a double-spaced copy of the input in the output file.
public class ProgramTest
public static void main (String[] args )
{
Scanner keyboard = new Scanner(System.in);
System.out.println("where to read?");
String in = keyboard.nextLine();
System.out.println("where to write?");
String out = keyboard.nextLine();
Scanner scanner = new Scanner(new File(in));
PrintWriter outputFile = new PrintWriter(out);
}
Thats what I have so far. What I dont know is how to make it do the last part to read the input file and make a double-spaced copy of the input in the output file.
well you can start by reading in the file?
private static void readFile(String inputFile) {
File file = new File(inputFile);
try {
Scanner scan = new Scanner(file);
//for example String s = scan.next(); would store next word
//doulbe d = scan.nextDouble(); would grab next double
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Once you read in the file sore the lines/numbers into variables?? Should not be to hard work with the read file i provided. Also remember what should you read in first ints or strings?
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();
}
I am getting this error when I try to run my program
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at studenttextwrite.StudentDAO.open(StudentDAO.java:37)
at studenttextwrite.StudentTextWrite.main(StudentTextWrite.java:33)
Java Result: 1
I am trying to write an object to a txt file 'student.txt'. I have checked that the text file is in the correct folder, and that I have lines to be read. The program is supposed to read line by line and then create an object from those lines.
here is what the code looks like, any help would be greatly appreciated thanks.
public class StudentDAO implements DAO {
ArrayList<Student> studentList = new ArrayList();
String outputFileName = "student.txt";
File outputFile = new File(outputFileName);
Scanner in;
public StudentDAO() throws DAOException {
try {
in = new Scanner(new BufferedReader(new FileReader(outputFile)));
} catch (FileNotFoundException ex) {
throw new DAOException(ex.getMessage());
}
}
#Override
public void open() {
while (in.hasNextLine()) {
String studentName = in.nextLine();
String studentClass = in.nextLine();
String teacher = in.nextLine();
String studentAge = in.nextLine();
int studentAgeInt = Integer.parseInt(studentAge);
studentList.add(new Student(studentName, studentClass, teacher,
studentAgeInt));
}
}
while (in.hasNextLine()) {
String studentName = in.nextLine();
String studentClass = in.nextLine();
String teacher = in.nextLine();
String studentAge = in.nextLine();
}
You are doing hasNextLine() check only once. But you are reading 4 lines in.nextLine();.
The problem is your code assume that each student record consists of four lines, but you have less number of lines for a particular student. Consider a file that consist of following entries (left number is the line number):
a1
che
b1
21
a2
che
b2
22
a3
chem
b3
running the following code will create a similar error you have faced as there are only three lines for the third (a3) student. Check your input files.
while(in.hasNextLine()){
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
System.out.println(" "+in.nextLine());
}