为什么我的文件没有被打开?

时间:2015-10-19 02:52:26

标签: java file

该文件位于源代码所在的根目录中。还有一个数字贴在路径变量的末尾会搞砸,或者你会怎么做?

有10个文件可供选择,它们都有相似的名称,但以不同的数字结尾。所以我考虑使用默认路径变量然后将数字附加到它然后执行文件名文件=新文件(路径+年+“。txt”)

知道为什么不提起它?

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;

public class nameRanker {

public static void main(String[] args) throws Exception {
    int skip = 0;
    int rank = 0;
    int year = 0;
    char gender = '0';
    String name = "";
    String compareName = "";
    Boolean found = false;

    Scanner input = new Scanner(System.in);

    System.out.print("Enter the year: ");  //try to catch mismatched input here (0-10)
    try { year = input.nextInt(); 

    System.out.print("\nEnter the gender: ");  //try to catch mismatched input here (M or F)
    gender = input.next().charAt(0);

    System.out.print("\nEnter the name: ");   //try to catch mismatched input here (no #)
    name = input.next();
    }

    catch (InputMismatchException e) {
              e.printStackTrace();
              System.err.println("Entered value does not match expected value. \n(Year must be integer, gender M or F, and name must be a string.)");
    }

    String path = "\\BabynamesrankingFiles\\Babynamesranking";
    File nameFile = new File(path + year + ".txt");   //throws IOexception if not found 
    //Scanner readFile = null;

    try (Scanner readFile = new Scanner(nameFile)){
    //readFile = new Scanner(nameFile);
    if(nameFile.canRead()){ //if the file is readable
        while(readFile.hasNext() && !found){    //while data in file

            if(gender == 'M'){      //if male only parse first two values 
                rank = readFile.nextInt();      //store rank
                compareName = readFile.next();      //grab name to compare
                found = (compareName == name) ? true : false;  //if name found break while loop
            }

            if(gender == 'F'){
                rank = readFile.nextInt();      //store the rank
                compareName = readFile.next();   //store the boy name
                skip = readFile.nextInt();      //store the total names value even though unused
                compareName = readFile.next();  //store the girl name to compare
                found = (compareName == name) ? true : false;  //if name found break while loop
            }
        } //end while loop

        if(!found){             //if name not found 
            System.out.println("The name " + name + "is not ranked in year " + year);
        }
        else{
            System.out.println("The name " + name + " is ranked " + rank + " in the year " + year);
        }
      }
    }

    catch(IOException ex){
        System.out.println("Error could not open file, check file path."); 
    }

    finally {   
    input.close();          //close scanner
    }
}
}

0 个答案:

没有答案
相关问题