【发布时间】:2015-06-08 15:29:34
【问题描述】:
它目前所做的是从文本文件中读取数据并以指定的方式输出它们。当我将它输出到控制台时,它会以所需的方式显示它,但是当我尝试将它输出到文本文件时,由于某种原因它只会写入循环的最后一行。这是我必须处理文件输出的代码:
public static void main(String[] args) throws FileNotFoundException {
String gt;
String gt2;
int gs1;
int gs2;
int total = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader("input.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
gt = words[0]; // read the home team
gt2 = words[1]; // read the away team
gs1 = Integer.parseInt(words[2]); //read the home team score
total = total + gs1;
gs2 = Integer.parseInt(words[3]); //read the away team score
total = total + gs2;
validresults = validresults + 1;
File file = new File("out.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
System.setOut(ps);
System.out.println(gt + " " + "[" + gs1 + "]" + " | " + gt2 + " " + "[" + gs2 + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
【问题讨论】:
-
将
FileOutputStream(等)部分移出循环 -
@Reimeus 在整个街区?
-
退出 while(s.hasNext()) 循环。所以在扫描仪下方,但在 while 循环上方。