【问题标题】:FileInputStream not reading first valueFileInputStream 没有读取第一个值
【发布时间】:2014-12-09 03:57:41
【问题描述】:

我需要读取的文件如下所示:

  • 30 15
  • 6 3
  • 12 20
  • 3 4

(不带项目符号)

inputStream 不是读取 30 和 15,而是读取所有其他的。

如何让 inputStream 读取第一行?

import java.io.*;
import java.util.*;

public class Program6 {
    //  private static Fraction [] fractionArray;
    public static void main(String[] args) throws FileNotFoundException, IOException {
        System.out.println("Please enter the name of the input file: ");


        Scanner inputFile = new Scanner(System.in);
        Scanner outputFile = new Scanner(System.in);

        String inputFileName = inputFile.nextLine();
        System.out.println("Please enter the name of the output file: ");
        String outputFileName = outputFile.nextLine();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
        FileWriter fileWriter = new FileWriter(outputFileName, true);
        //Declaring an inputstream to get file
        Scanner inputStream = new Scanner(new FileInputStream(inputFileName));


        //while the file still has a line
        while (inputStream.hasNextLine()) {
            String theLine = inputStream.nextLine();
            if (theLine.length() >= 0) {
                //declares a numerator and denominator from the file
                int num = inputStream.nextInt();
                int denom = inputStream.nextInt();
                //new fraction from file
                Fraction fract = new Fraction(num, denom);
                fract.reduce();
                System.out.println(fract);
                fileWriter.write("" + fract + "\r\n");
            }
        }

        //closes streams and flushes the file writer
        fileWriter.flush();
        fileWriter.close();
        inputStream.close();
    }
}

【问题讨论】:

    标签: java string file java.util.scanner fileinputstream


    【解决方案1】:

    这里的问题是Scanner.nextLine() 消耗来自 InputStream 的输入行。然后,使用 Scanner.nextInt() 返回从同一个 InputStream 消费 - 它不会从 nextLine() 返回的值消费。

    所以,使用一个或另一个。

    如果使用nextLine() 方法,则需要解析包含该行的字符串以提取值。使用scanner.nextInt(),文件中的整数值立即可用。唯一的损失是您会失去对值是在同一行还是在不同行上的知识。

    【讨论】:

    • 并非如此。我会补充一点细节。
    • 我这样做了:String theLine = inputStream.nextLine(); int num = Integer.parseInt(theLine); int denom = Integer.parseInt(theLine);我得到一个 NumberFormatException
    • 是的,因为每次调用 parseInt() 都会使用整行 - 它们不会从输入流中消耗。尝试从客观的角度考虑您正在使用的代码是如何工作的,然后它会如何为您工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多