【发布时间】: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