简体   繁体   English

为什么readLine()没有阻塞?

[英]How come readLine() is not blocking?

Given the following code, the first call to readLine() is not blocking, both "Enter name:" and "Enter address:" are printed at the same time, and address gets assigned to whatever is entered. 给定以下代码,对readLine()的第一次调用不会阻塞,同时显示“输入名称:”和“输入地址:”,并且将地址分配给所输入的内容。 Why? 为什么? I've tried putting them in separate try blocks, getting rid of the loop and generally reordering things. 我试过将它们放在单独的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.");
    }

}

} }

This is because of this line: 这是因为此行:

c = br.read();

This does not consume the new-line character that is produced by pressing ENTER . 这不会占用通过按ENTER产生的换行符。

To solve this issue, use this instead: 要解决此问题,请改用以下方法:

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

Over and above whats already been said, for what you're trying to do I suggest using the Console instead: 除了已经说过的话,对于您要执行的操作,我建议改为使用控制台:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM