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

时间:2015-04-21 03:00:56

标签: 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);

    }
}

2 个答案:

答案 0 :(得分:3)

使用filename.trim().length()>0添加一个额外条件(filename = br.readLine()) !=null。由于!= null不会检查空格。为什么你放(而真)。根据您当前的代码,它没用。

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...");
}

答案 1 :(得分:1)

到达流末尾时,

BufferedReader会返回null。当用户输入空行时,它返回""(长度为0的空字符串)。

因此,您应该将循环条件更改为:

while (!(filename = br.readLine()).equals(""))