用扫描仪从文件中读取

时间:2015-10-26 17:24:20

标签: java java.util.scanner

我无法从文本文件(amazon.txt)中读取一行:

ClassFek的TextFile和read方法(书):

   BOEK Harry Mulisch, De Aanslag, 9023466349, Bezige Bij, 246, 2010, 19.95
   BOEK Dan Brown, De Da Vinci Code, 9024562287, Luitingh, 432, 2009, 12.49
   CD Foo Figthters, Wasting Light, 0886978449320, Sony, 2011, 11.95
   MP3 Hooverphonic, Reflection, 0888837802826, Sony, 2013, 15.00, 165



public static Boek read(Scanner sc){

    sc.useDelimiter(", ");
    String tkArtiest = sc.next();
    String tkTitel = sc.next();
    long tkISBN = sc.nextLong();
    String tkUitgever = sc.next();
    int tkAantalBladzijden = sc.nextInt();
    int tkJaarUitgave = sc.nextInt();
    long tkPrijs = sc.nextLong();

    return new Boek(tkArtiest, tkTitel, tkISBN, tkUitgever, tkAantalBladzijden, tkJaarUitgave, 0);

}

这是我从类目录中读取的方法,它将第一个标记作为类型读取,然后将扫描程序发送到上面的类Boek中读取的方法。 (类目录保留了书籍和文件的读者,因此没有完成) 但是我似乎无法从我的文件中读取第一行文本,因为我遇到了 19.95 ,必须将其视为 long ,但读取( 19.95BOEK Dan Brown )作为一个标记。有什么技巧可以读作19.95作为一个标记?

    public static Catalogus read(File inFile) {

    Catalogus catalog = new Catalogus();

    try {
        Scanner sc= new Scanner(inFile);
        String type = sc.next();

        if (type.equals("BOEK")) {
            catalog.addEntertainment((Boek.read(sc)));
        } else {
            System.out.println("type != BOEK or ERROR");
        }

    } catch (FileNotFoundException e) {
        System.out.print("Problem reading file.");
        e.printStackTrace();
    }

    return catalog;

}

2 个答案:

答案 0 :(得分:1)

显然scanner读了一遍。所以你可以做的是首先读取一行,然后解析该行的字段。

    try {
        Scanner sc= new Scanner(inFile);
        sc.useDelimiter( System.getProperty("line.separator") );

        while (sc.hasNext()) {

            String line =  sc.next();
            System.out.println(line);
            Scanner scanline = new Scanner(line);

            String type = scanline.next();

            if (type.equals("BOEK")) {
                catalog.addEntertainment((Boek.read(scanline)));
            } else {
                System.out.println("type != BOEK or ERROR");
            }

        }

    } catch (FileNotFoundException e) {
        System.out.print("Problem reading file.");
        e.printStackTrace();
    }

此外,我在Book.read()

进行了一些小改动
long tkPrijs = sc.nextLong();

更改为:

double tkPrijs = sc.nextDouble();

并运行:

BOEK Harry Mulisch, De Aanslag, 9023466349, Bezige Bij, 246, 2010, 19.95
addEntertainment() added this Boek to Catalogue
BOEK Dan Brown, De Da Vinci Code, 9024562287, Luitingh, 432, 2009, 12.49
addEntertainment() added this Boek to Catalogue
CD Foo Figthters, Wasting Light, 0886978449320, Sony, 2011, 11.95
type != BOEK or ERROR
MP3 Hooverphonic, Reflection, 0888837802826, Sony, 2013, 15.00, 165 
type != BOEK or ERROR

答案 1 :(得分:0)

使用nextLine而不是next用于tkArtiest,tkTitel,tkUitgever