我正在制作这个应该从输入文件读取然后创建输出文件的程序。
输入文件(portlandvip2.txt):
法院50
专栏10
Club 25
Rascal Conway 10 Box
Loretta Barrett 3 Court
Loras Tyrell 5俱乐部
Margaery Tyrell 8 Box
Roslin Frey 2 Box
Sansa Stark 2 Club
Jon Snow 5 Club
Edmure Tully 3 Box
Joffrey Baratheon 20 Court
Stannis Baratheon 4 Club
Jaime Lannister 2 Box
Cersei Lannister 1 Court
Beric Dondarrion 8 Court
Balon Greyjoy 16 Box
Olenna Tyrell 4 Court
梅斯泰瑞尔5盒
Tyrion Lannister 2俱乐部
Sandor Clegane 2 Court
Gregor Clegane 6 Club
Samwell Tarly 3 Club
Petyr Baelish 6 Court
这是一个输出文件应该是什么样子的示例(portland2out.txt):
法院50美元
Box $ 10
Club $ 25
Rascal Conway $ 100.00
Loretta Barrett $ 150.00
我遇到的问题是打印的所有输出文件都是Petyr Baelish。
到目前为止,这是该计划:
import java.util.Scanner;
import java.io.*;
import java.io.Writer;
public class WebberProject2
{
public static void main(String[] args) throws IOException
{
Scanner inputFile = new Scanner(System.in);
File inputScanner = new File("portlandvip2.txt");
Scanner scanner = new Scanner(new File("portlandvip2.txt"));
while(scanner.hasNext())
{
String firstName = scanner.next();
String lastName = scanner.next();
PrintWriter outputFile = new PrintWriter("portland2out.txt");
outputFile.println(" " + firstName + " " + lastName);
scanner.nextLine();
inputFile.close();
outputFile.close();
}
}
}
答案 0 :(得分:2)
您正在循环中打开和关闭输出文件,每次执行循环时都会重写一行。在循环外部使用PrintWriter及其close()方法。此外,您还有其他资源也在循环中关闭。试试这种方法:
// ...
Scanner inputFile = new Scanner(System.in);
File inputScanner = new File("portlandvip2.txt");
Scanner scanner = new Scanner(new File("portlandvip2.txt"));
PrintWriter outputFile = new PrintWriter("portland2out.txt");
while(scanner.hasNext())
{
String firstName = scanner.next();
String lastName = scanner.next();
outputFile.println(" " + firstName + " " + lastName);
scanner.nextLine();
}
outputFile.close();
inputFile.close();
scanner.close();
// ...
答案 1 :(得分:1)
您的代码看起来不完整。虽然循环未关闭。你也在关闭循环中的文件,这会抛出异常。使用以下代码作为基础并根据您的要求进行调整。例如,使用Scanner方法nextInt()来读取数字标记,并在写入输出文件时在它们前面加上$符号。
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class TestScanner{
public static void main(String[] args)
{
Scanner scanner = null;
PrintWriter outputFile = null;
try{
scanner = new Scanner(new File("portlandvip2.txt"));
outputFile = new PrintWriter("portland2out.txt");
String firstName, lastName;
int num = 0;
while(scanner.hasNext())
{
firstName = scanner.next();
if(scanner.hasNextInt()){
num = scanner.nextInt();
}
lastName = scanner.next();
outputFile.println(" " + firstName + " " + lastName + " $ " + num);
scanner.nextLine();
}
}catch(IOException e){
System.out.println("exception:"+e);
}finally{
scanner.close();
outputFile.close();
}
}
}