我尝试在Java中使用File and Scanner打开CSV文件,但我无法使用Scanner打开它。以下是代码,任何想法? 相关代码位于parseFile函数
中import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class CIS350HW1 {
/**
* @param args
*/
public static void main(String[] args) {
boolean quit = false;
int year = 0;
while(quit == false){
printMenu();
Scanner sc = new Scanner(System.in);
String str = sc.next().toUpperCase();
System.out.println(str);
if (str.equals("Q")) {
System.out.println("Good bye");
quit = true;
}
else if (str.equals("3")) {
parseFile(args[0], Integer.parseInt(str), year);
}
else if (str.equals("2") || str.equals("1")) {
System.out.println("Please enter the year: "); //remember might not be println
try {
year = Integer.parseInt(sc.next());
} catch(NumberFormatException e) {
System.out.print("Invalid formatted input. ");
}
if (year < 1920 || year > 2010){
System.out.println("Not a valid year.");
System.out.println();
}
parseFile(args[0], Integer.parseInt(str), year);
}
else {
System.out.println("That is not a valid selection.");
}
}
}
/**
* prints the menu options to the consul.
*/
public static void printMenu() {
System.out.println("Welcome to the Oscars database!");
System.out.println();
System.out.println("Please make your selection:");
System.out.println("1: Search for best picture award winner by year");
System.out.println("2: Search for best picture award nominees by year");
System.out.println("3: Search for actor/actress nominations by name");
System.out.println("Q: Quit");
}
public static void parseFile(String args, int n, int year) {
File file = new File(args);
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Could not open the file for some reason.");
}
while(input.hasNext()) {
String nextLine = input.nextLine();
String token[] = nextLine.split(",");
if (n == 1) {
String tempYear[] = token[0].split(" ");
if (Integer.parseInt(tempYear[0]) == year
&& token[1].equals("Best Picture")
&& token[3].equals("YES")) {
System.out.println(token[2]);
}
}
}
input.close();
}
}
请注意,代码还没有做任何事情,试图弄清楚为什么try / catch永远不会起作用。 谢谢!
答案 0 :(得分:0)
如果您使用命令行来运行程序(java CIS350HW1 file.csv),那么该文件必须位于同一文件夹中。
但是如果您从IDE(Eclipse或其他)运行程序,那么您的文件必须位于项目的类路径中。