【问题标题】:reading data from file and breaking it into tokens从文件中读取数据并将其分解为令牌
【发布时间】:2014-12-08 21:18:26
【问题描述】:

我在读取文本文件后使用以下代码将文本文件的输入分解为令牌:

String input;
while(true)
{
    input = bin.readLine(); 
    if (input == null) 
    {
        System.out.println( "No data found in the file");
        return 0;
    }
    break;
}

StringTokenizer tokenizer = new StringTokenizer(input);

然后:

for (int i=0; i < numAtt; i++) 
{
    attributeN[i]  = tokenizer.nextToken();
}

我不明白为什么 attributeNames 只在文本文件的第一行获取标记,而不是 while(true) 继续读取整个文件吗?还有没有办法避免 while(true) 并使用 break 来终止它?

【问题讨论】:

    标签: java token stringtokenizer


    【解决方案1】:

    if (input == null) { } 之后的 break 正在中断,因此您的代码只读取一行。

    还有一种方法可以避免 while(true) 并使用 break 来 终止它?

    这样做:

    while ((input = bin.readLine()) != null) {
        //split input line here 
    }
    

    另外,考虑使用String#split() 将行拆分为标记。分隔符, 的示例:

    String attributeNames[] = input.split(",");
    

    【讨论】:

      【解决方案2】:

      最好的方法是使用:

       String splittedString[] = input.split("the separator");
      

      Oracle 推荐的。

      【讨论】:

        【解决方案3】:

        您只是想从第一行获取令牌吗?如果是这样,您根本不需要 while 循环。只需删除开头的while { 和结尾的break; }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-08-19
          • 2013-07-23
          • 1970-01-01
          • 2019-05-15
          • 1970-01-01
          • 2016-04-11
          相关资源
          最近更新 更多