试图从文件中读取数据(文件每两行包含换行符)

时间:2014-07-19 19:45:16

标签: java file-io

首先,这是数据文件的样子

  

5165168416516988798484984984984984
  9898798798798

  1556516846516518498
  51688484979789798798798491

我需要在换行符之前读取两行(我可以做得很好),然后继续读两遍,直到文件结束。保证偶数配对,所以最后不会有单独的线。我的问题是尝试读取前两行之外的文件。

code
try {
    Scanner input = new Scanner (file);
    while (input.hasNextLine()) {
        String number1 = input.nextLine();
        String number2 = input.nextLine();

        System.out.println("String: " + number1);
        System.out.println("String: " + number2);

        System.out.println(number1 + " " + number2);

        number1= input.nextLine();
        number2= input.nextLine();
    }
} 

到目前为止我做了什么。它只适用于没有换行符的情况,尽管它仍然会在结尾处发出异常(“No Line Found”)。

只要在文件中找到第一个中断,就会发生此异常。如何使整个文件以我想要的方式读取? (抓住两条线,对它们做点什么。抓住接下来的两条线,做点什么......一直到最后)

4 个答案:

答案 0 :(得分:1)

确定。我们试试吧。

try {
    Scanner input = new Scanner (file);

    // input.hasNextLine() checks if there are more lines that can be read from
    // the file. If there is a line, hasNextLine() will return true, and the code
    // inside the while block will be executed.
    // Then execution will come back here to perform the check again. This
    // goes on until there are no more lines to consume.
    while (input.hasNextLine()) {

        // We are going to read two numbers from file.
        // Ideally, we should check if there a line available before reading
        // each of these lines. But since you confirm that the file will
        // always have multiple number of triplets containing two lines
        // with numbers, followed by a blank line, we are not going to
        // call input.hasNextLine() here.
        String number1 = input.nextLine();
        String number2 = input.nextLine();

        // Now, two numbers are read, read the next (empty) line to a variable
        // but we will not use it anywhere.
        String emptyLine = input.nextLine();
        // ...or we could read it, but just discard it without assigning it to a variable
        // input.nextLine();

        // Print what we read to the output, like a boss.
        System.out.println("String: " + number1);
        System.out.println("String: " + number2);
        System.out.println(number1 + " " + number2);

        // This is not needed here (see below to understand why):
        //number1= input.nextLine();
        //number2= input.nextLine();

        // after the following brace (}), execution will go back to the start
        // of the while loop. and if there are more lines to be read, code
        // inside while loop will be executed again.
    }
}

希望这可以解决它。

警告:为使此代码在没有错误的情况下正常工作,您的输入文件必须在其中最后一个数字对后面包含一个空行。否则它将抛出NoSuchElementException

答案 1 :(得分:0)

这使用了另一种每行读取文本文件的方式:

try {
        BufferedReader newBufferedReader = Files.newBufferedReader(Paths.get("PathToTextFile.txt"), Charset.defaultCharset());
        while (newBufferedReader.ready()) {
            System.out.println(newBufferedReader.readLine());
        }
        newBufferedReader.close();
    } catch (IOException ex) {
        Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
    }

答案 2 :(得分:0)

我已经完成了完整的代码。当此代码读取超过最后一行时,将抛出异常NoSuchElementException但是,我们捕获此异常并让用户知道已到达文件末尾。或者,你可以做任何事情。但是,这并不好。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.util.Scanner;

public class Filez {

    public static void main(String[] args) {

        File file = null;
        Scanner input = null;

        try {

            file = new File("C:/Temp/two.txt");
            input = new Scanner(file);
            String line = "";   
            int count = 0;

            while (true) {

                for(count = 1; count < 3; count++){             
                    line = line + input.nextLine() + ", ";
                }

                System.out.println(line);
                input.nextLine();
                line = "";

            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch(NoSuchElementException e){
            System.out.println("\n\nReached end of file...\n");
        }
    }
}

答案 3 :(得分:0)

你可以忽略空白行,如果它们存在与否则无关紧要。

public static String readNonBlankLine(Scanner in) {
    while(in.hasNextLine()) {
        String s = in.nextLine();
        if (!s.trim().isEmpty())
            return s;
    }
    return null;
}

try {
    Scanner input = new Scanner (file);
    while (input.hasNextLine()) {
        String number1 = readNonBlankLine(input);
        String number2 = readNonBlankLine(input);

        System.out.println("String: " + number1);
        System.out.println("String: " + number2);

        System.out.println(number1 + " " + number2);
    }
}