为什么这段代码不会读取文件?

时间:2015-09-13 17:42:11

标签: java android macos for-loop

我正在尝试创建一个程序,该程序从名为category的文件中读取,然后通过for循环写入控制台。这是代码:

Clients

以下是控制台中的错误:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import static java.lang.System.out;

class ShowOccupancy{
    public static void main(String args[])
    throws FileNotFoundException{ 
        Scanner diskScanner = 
                new Scanner (new File("Clients"));              
        out.print("Room Number");
        out.print("/t");
        out.println("Guests");
        for (int roomNum=0; roomNum<10; roomNum++)
        {
            out.print(roomNum);
            out.print("/t");
            out.print(diskScanner.nextInt());                   
        }
        diskScanner.close();
    }                               
} 

我为java项目创建了一个Exception in thread "main" java.io.FileNotFoundException: Clients (No such file or directory) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(FileInputStream.java:195) at java.io.FileInputStream.<init>(FileInputStream.java:138) at java.util.Scanner.<init>(Scanner.java:611) at ShowOccupancy.main(ShowOccupancy.java:11) 文件。

1 个答案:

答案 0 :(得分:0)

这是一个如何阅读文本文件的示例,希望它有所帮助。

public static void main(String[] args) {
    try {
        Scanner reader = new Scanner(new File("FILE-PATH-HERE/clients.txt"));

        //Prints lines
        while (reader.hasNextLine()) {
            System.out.println(reader.nextLine());
        }

        //Prints tokens
        /*
         while (reader.hasNext()) {
         System.out.println(reader.next());
         }
         */
        reader.close();
    } catch (FileNotFoundException ex) {
        //Print error
        ex.printStackTrace();
    }
}