java - 为什么我在用 Java 读取文本文件时会循环?

标签 java loops file-io while-loop

为了测试,我在一个文本文件中得到了三个名字。

Joe       ,Smith
Jim       ,Jones
Bob       ,Johnson

我通过在 while 循环的末尾添加第二个 s=reader.readLine(); 来修复永恒循环,但是当我运行下面的代码时,我得到以下输出:

JoeSmith
JoeSmith
JimJones
JimJones
BobJohnson
BobJohnson

如何防止重名?我的第二个 s=reader.readLine(); 放错了吗? * 废话。没关系。我正在打印源数据和从中创建的数组字段。哎呀。

import java.nio.file.*;
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
import java.text.*;
import javax.swing.JOptionPane;
//
public class VPass
{
    public static void main(String[] args)
    {
        final String FIRST_FORMAT = "          ";
        final String LAST_FORMAT = "          ";
        String delimiter = ",";
        String s = FIRST_FORMAT + delimiter + LAST_FORMAT ;
        String[] array = new String[2];
        Scanner kb = new Scanner(System.in);
        Path file = Paths.get("NameLIst.txt");
        try
        {    
            InputStream iStream=new BufferedInputStream(Files.newInputStream(file));
            BufferedReader reader=new BufferedReader(new InputStreamReader(iStream));
            s=reader.readLine();
            while(s != null)
            {
                array = s.split(delimiter);
                String firstName = array[0];
                String lastName = array[1];
                System.out.println(array[0]+array[1]+"\n"+firstName+lastName);
                s=reader.readLine();
            }
    }
    catch(Exception e)
    {
        System.out.println("Message: " + e);
    }
   }
  }

最佳答案

您永远不会在第一次循环迭代后更新 s

您的代码需要更多地遵循:

while ((s = reader.readLine()) != null)
{
  array = s.split(delimiter);
  String firstName = array[0].trim();
  String lastName = array[1].trim();
  System.out.println(array[0]+array[1]+"\n"+userName+password);
}

编辑:根据 Sanchit 的评论添加了 trim() 建议。


问题改变后的后续编辑:

I fixed the eternal looping by adding a second s=reader.readLine(); at the end of my while loop, but when I run the code below, I get the following output:

JoeSmith

JoeSmith

JimJones

JimJones

BobJohnson

BobJohnson

如果我们查看您的代码:

while(s != null)
{
  array = s.split(delimiter);
  String firstName = array[0];
  String lastName = array[1];
  System.out.println(array[0]+array[1]+"\n"+firstName+lastName);   // <-- this prints 2 lines of output
  s=reader.readLine();
}

...您会看到每次循环迭代输出 2 行输出。

关于java - 为什么我在用 Java 读取文本文件时会循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10343706/

相关文章:

java - Android主线程与其他线程之间的通信

java - Websphere 8.5 : Application is not installed inside "installedApps" directory

java - 在 Eclipse 中 Maven build 和 Maven build... 有什么区别?

python - 循环不会像读取字符串中的其他单词那样读取第一个单词

c - 为什么命令提示符在开始之前显示数字?

java - @RequestMapping 不起作用 - 没有找到处理程序方法

loops - 为什么我的 Common Lisp 循环只适用于普通代码?

jquery 循环创建具有保留值的元素

scala - 在 Scala 2.8 中,如何向文件写入(追加)一行?我应该使用 Java 类(class)还是为此使用原生的 Scala 函数?

java - Spring 不归档属性文件