java - 从文件中读取数据并将其分解为标记

标签 java token stringtokenizer

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

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 来终止它?

最佳答案

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

Also is there a way to avoid the while(true) and using break to terminate it?

这样做:

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

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

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

关于java - 从文件中读取数据并将其分解为标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27367120/

相关文章:

java - 即使绘制新文本,也设置一次 swing 应用程序的默认字体

c - ';' token 之前的错误 : expected ',' , ')' 或 '&'

c++ - 解析字符串并将标记作为参数传递

java - HttpClient - 如何设置指纹和_csrf?

JAVA : Reading txt and take elements with StringTokenizer

java - Spring 框架 1.1.2 - 具有挑战性...使用命令行 javac 编译器,无需构建工具(Maven 或 Gradle 等)

java - 为什么@FormParam 不支持content=type=application/json?

java - JDK > 8 中带有 OPTIONS header 的 Jersey JAX_RS 中存在错误?

java - 字符串分词