java - 在命令提示符输入中从 BufferedReader 读取空值

标签 java bufferedreader

我正在尝试从命令行读取用户的输入。对于 filename 的输入,程序应该在检测到用户提交了空白值时退出。

但是,无论用户输入是否包含任何内容,程序总是会转到“内部读取文件”代码。它永远不会执行“程序将立即退出”代码。我尝试了不同的编码方式,所有方式都得到了相同的结果。有什么问题吗?

public static void main(String[] args) throws Exception {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String collection; 
    String filename;

    System.out.println("Enter the collection name: ");
    collection = br.readLine();

    String urlString = "http://localhost:8983/solr/" + collection;
    solr = new HttpSolrClient(urlString);

    doc1 = new SolrInputDocument ();

    while (true){

        System.out.println("Enter the file name: ");
        while ((filename = br.readLine()) !=null) {
            System.out.println("Inside reading file ");
            parseUsingStringTokenizer(filename);
            System.out.println("Enter the file name: ");
        }
        System.out.println("Program will exit now...");
        System.exit(0);

    }
}

最佳答案

使用 (filename = br.readLine()) !=null 添加一个额外的条件 filename.trim().length()>0。因为 != null 不会检查空格。以及为什么你把 while(true).根据您当前的代码,它是无用的。

public static void main(String[] args) throws Exception {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String collection; 
    String filename;

    System.out.println("Enter the collection name: ");
    collection = br.readLine();

    String urlString = "http://localhost:8983/solr/" + collection;
    solr = new HttpSolrClient(urlString);

    doc1 = new SolrInputDocument ();

    System.out.println("Enter the file name: ");
    while ((filename = br.readLine()) !=null && filename.trim().length()>0){
        System.out.println("Inside reading file ");
        parseUsingStringTokenizer(filename);
        System.out.println("Enter the file name: ");
    }
    System.out.println("Program will exit now...");
}

关于java - 在命令提示符输入中从 BufferedReader 读取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29762122/

相关文章:

java - Java中的void f(Class c) 和 void f(Class<?> c) 有什么区别吗?

Java - 将形状添加到框架

java - 套接字:BufferedReader readLine() block

java - 如何防止Java将条形码转为科学计数法

java - 使用 BufferedReader 读取所有行而不是清空它

java - 如何在java中设置google protobuf重复字段

java - 暴力破解java递归密码

java - 强制 JUnit gradle 任务在项目中使用 jar 构建

java - 从慢速流读取时,BufferedReader.readLine() 是否可能不读取整行?

java - 使用 Java IO 搜索并打印特定行