扫描仪只读取第二行文本文件

时间:2015-10-28 20:05:34

标签: java string text-files

代码

public class Login {

    private String nickname;
    private static String line;

    public Login(String nickname) throws IOException {
        this.nickname = nickname;

        try {
            Scanner input = new Scanner(new File(nickname + ".acc"));
            while (input.hasNextLine()) {
                line = input.nextLine();
            }
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[]args) throws IOException {
        new Login("example");
        System.out.println(line);
    }
}

我有问题。如果我使用此代码,我的输出只会说34567.但我的文本文件包含:

example
34567

如何修复它,扫描程序是否可能将文本文件中的两行文本输出到单独的字符串?

4 个答案:

答案 0 :(得分:3)

你的问题在于这段代码:

// loop until the input has no more lines
while (input.hasNextLine()) {
    // PLACE the current line from the file into the line variable
    line = input.nextLine();
}

您将始终覆盖最后一行读取的line变量。这导致您的程序只存储文件的最后一行。

最简单的解决方法是将该行附加到现有变量。

// loop until the input has no more lines
while (input.hasNextLine()) {
    // APPEND the current line from the file into the line variable
    line += input.nextLine() + "\n"; // append a newline...
}

您还需要初始化line变量,在您的while循环之上,您只需将其初始化为空字符串

line = "";
while(...) ...

但是,这会在line变量中增加1个新行。更好的方法是只读取文件内容而不是使用扫描仪,请参阅此问题以获取更多信息How do I create a Java string from the contents of a file?

答案 1 :(得分:2)

line = input.nextLine();

在这里,您要覆盖之前阅读过的内容。 您可以将新行添加到行变量中,如下所示:

line += input.nextLine();

如果您想在读取的每一行之后换行,可以在每行的末尾添加换行符:

line += input.nextLine() + "\n";

答案 2 :(得分:0)

这里的问题在于您的while循环。 while (input.hasNextLine())告诉程序运行循环,直到扫描程序到达文件的最后一行。由于循环中唯一的代码行将line的值设置为等于文件中的下一行文本,因此它将一直保持更改line的值,直到它到达最后一行。解决此问题的最简单方法是将System.out.println(line)移到while循环内,跟随line = input.nextLine()

或者,如果您希望在主方法中保留println()方法,则可以让while循环将每行文本存储到ArrayList<String>中,然后使用{{ 1}}循环在main方法中迭代它并打印每个元素,但这需要使代码比简单地移动一行代码更复杂,并且无论如何都会产生完全相同的输出。

答案 3 :(得分:0)

From your comment:

can I store both lines of my string 'line', into two strings?

I made this, using a String array. You should use a List because of performance, as @ug_ suggested

The following example shows how to use the String array. I'll suggest you to try using a List yourself, so you learn something new.

The last part is commented, since, as you said you're a Java starter you're maybe be more familiar with a for-loop instead a for-each loop, both for loops in the code work exactly the same way. I recommend you to learn about both them too.

Edit

As of @ug_ comment I made a new approach which ended being an edit to his own answer. (So his answer is actually the correct one). It adds a new line \n after it reads each line on the file, then it splits by this line break and stores it into an array, after that it just prints it out:

import java.util.Scanner;
import java.io.*;
public class Login {

    private String nickname;
    private static String lines[];

    public Login(String nickname) throws IOException {
        this.nickname = nickname;

        try {
            Scanner input = new Scanner(new File(nickname + ".acc"));
            String line = "";
            while (input.hasNextLine()) {
                line += input.nextLine() + "\n"; //Add a new line to our string
            }
            lines = line.split("\n"); //Split the string and store it into the array
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[]args) throws IOException {
        new Login("example");
        for (String s : lines) { //print each element of the array.
            System.out.println(s);
        }
        /*for (int i = 0; i < lines.length; i++) {
            System.out.println(lines[i]);
        }*/
    }
}

The output is:

example
34567