Running a Java program with input from a file
I am writing a program that reads the input from a file and then prints it to the screen. When I run it without taking the input from the file, it works perfectly fine. However, every time I try to run it from the file it gives me an "Exception in thread "main" java.util.NoSuchElementException: No line found at" error that occurs every place the input is suppose to be read. I have no idea what is going on.
This program is suppose to take the input from the user, create a Photo object, and then print the information to the screen. Everything runs fine when I am entering the information manually but when I try to use java PhotoTest < test.dat to get the input for a file it gives this error message:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at PhotoTest.readPhoto(PhotoTest.java:31)
at PhotoTest.main(PhotoTest.java:74)
My code that has input:
private static Photo readPhoto(Scanner scanner) throws ParseException
{
Date dateTaken;
Scanner scan = new Scanner(System.in);
String subject = scan.nextLine();
subject = subject.trim();
String location = scan.nextLine();
location = location.trim();
String date = scan.nextLine();
date = date.trim();
if (date.equals("")){ //if the date is empty it is set to null
dateTaken = null;
}
else { //if a date is entered, it is then parsed
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
dateTaken = df.parse(date);
}
String file = scan.nextLine();
file = file.trim();
File photoFile = new File(file);
//creates a Photo object from the information entered
Photo Photo = new Photo(subject, location, dateTaken, photoFile);
return Photo;
}
public static void main(String[] args) throws ParseException
{
boolean endprogram = false;
Scanner scan = new Scanner(System.in);
//creates a loop so that the user may enter as many photos as they wish
while (!endprogram)
{
System.out.println("Would you like to enter a photo (y/n)?");
//if the input is anything other than y, the program ends
if(!scan.next().equalsIgnoreCase("y"))
{
endprogram = true;
}
else
{
System.out.println(readPhoto(scan));
}
}
}
Everything runs fine when I am entering the information manually but when I try to use java PhotoTest < test.dat
to get the input for[sic?] a file [...]
Does test.dat
contain the "y"
confirmations too? When you pipe in a file for stdin
, the content of that file must be in legal format as if it was typed in manually.
Also, you are creating another Scanner
instance for stdin
even though one is already passed to readPhoto
. Are you sure you need to do this?
In your file you need a carriage return in the last line. That would be the equivalent to what you are typing manually. Note that when you are typing, in the last line you press enter.
链接地址: http://www.djcxy.com/p/17208.html上一篇: Java扫描程序不通过整个文件
下一篇: 使用文件输入运行Java程序