为什么readLine()没有阻塞?

时间:2013-02-17 22:10:11

标签: java

给定以下代码,第一次调用readLine()不会阻塞,同时打印“输入名称:”和“输入地址:”,并将地址分配给输入的内容。为什么?我已经尝试将它们放在单独的try块中,摆脱循环并通常重新排序。

public class AddressReader {

public static void main(String[] args) {

    Path file = Paths.get("d:/java IO/addresses.txt");

    try {
        Files.createDirectories(file.getParent());
    } catch (IOException e) {
        System.err.println("Error craeting directory: " + file.getParent());
        e.printStackTrace();
        System.exit(1);
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int c = 0;
    try {
        System.out.println("<a>dd an entry or <r>ead entries");
        c = br.read();
    } catch (IOException e) {
        System.out.println("An error has occured, try again");
    }
    switch (c) {
    case 'a':
        String name = null;
        String address = null;

        while (name == null || name == "" || address == null || address == "") {
            try {
                System.out.println("Enter name:");
                name = br.readLine();
                System.out.println("Enter address:");
                address = br.readLine();
            } catch (IOException e) {
                System.out.println("An error has occured, try again");
            }
            System.out.println("name = " + name);
            System.out.println("address = " + address);
        }
        //writeEntry(file, name, address);
        break;
    case 'r':
        //readEntries(file);
        break;
    default:
        System.out.println("Invalid entry, try again.");
    }

}

}

2 个答案:

答案 0 :(得分:3)

这是因为这一行:

c = br.read();

这不会消耗按 ENTER 生成的换行符。

要解决此问题,请改用:

c = br.readLine().charAt(0);

答案 1 :(得分:0)

已经说过,对于你想要做的事情,我建议改用控制台:

Console console = System.console();
String name = console.readLine("Create a name.");
char[] password = console.readPassword("Create a password.");
System.out.println(name + ":" + new String(password));