我得读一份年度最佳女演员和电影的档案。然后使用该文件创建两个新文件,一个包含年份和女演员,另一个包含年份和电影。该文件如下所示:
2002 Nicole Kidman
The Hours
2003 Charlize Theron
Monster
2004 Hilary Swank
Million Dollar Baby
2005 Reese Witherspoon
Walk the Line
2006 Helen Mirren
The Queen
2007 Marion Cotillard
La Vie en Rose
2008 Kate Winslett
The Reader
2009 Sandra Bullock
The Blind Side
2010 Natalie Portman
The Black Swan这就是我到目前为止所知道的:
import java.io.*;
import java.util.*;
public class BestActress{
public static void main(String[] args)throws FileNotFoundException{
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(new File("BestActress.txt"));
while(reader.hasNextLine()){
int yearNumber=reader.nextInt();
String text=reader.nextLine();
actressLine(text, yearNumber);
String textt=reader.nextLine();
movieLine(textt, yearNumber);
}
}
public static void actressLine(String text, int year)throws FileNotFoundException{
PrintWriter writer = new PrintWriter(new File("YearBestActresses.txt"));
Scanner data = new Scanner(text);
while (data.hasNext()){
String actressName=data.nextLine();
writer.println(year+actressName);
writer.close();
}
}
public static void movieLine(String textt, int year)throws FileNotFoundException{
PrintWriter writer = new PrintWriter(new File("YearBestActresMovies.txt"));
Scanner data=new Scanner(textt);
while(data.hasNext()){
String movieName=data.nextLine();
writer.println(year+" "+movieName);
writer.close();
}
}
}创建的文件只有最后一年,所以2010年的Natalie Portman和2010年的黑天鹅。
发布于 2015-03-03 01:58:16
你的程序中有几个问题。
首先也是最重要的是,当每个方法收到一行文本时,它会打开一个编写器,写入字符串的内容,然后关闭编写器。
默认情况下,打开编写器会清除文件。如果其中有数据是在前一次迭代中写入的,则会将其删除。此外,打开和关闭都是繁重的操作,应该只在需要的时候进行。
您应该做的是在进入main中的读取循环之前打开两个要写入的文件,并将编写器对象作为参数传递给您的方法。然后,在这些方法中,您可以只将一行代码写入文件。
在循环结束后关闭这两个文件。所有这些都最好使用try with resources构造来完成。
其他问题:
if ( reader.hasNextLine() )中。这确保了还有下一行。之后更改标志
发布于 2015-03-03 01:57:16
这是因为您每次编写新行时都会重新创建PrintWriter对象。每次执行此操作时,它都会删除并重新创建该文件。这就是为什么你只能在你的文件中看到最后的输出。
预先创建编写器,并将它们传递到编写行的方法中。(当然,您还需要将close()方法移到外部方法中。)如下所示:
编辑:根据@laune在评论中的建议,简化了actressLine和movieLine。
import java.io.*;
import java.util.*;
public class BestActress {
public static void main(String[] args)throws FileNotFoundException{
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(new File("BestActress.txt"));
PrintWriter writer1 = new PrintWriter(new File("YearBestActresses.txt"));
PrintWriter writer2 = new PrintWriter(new File("YearBestActresMovies.txt"));
while(reader.hasNextLine()){
int yearNumber=reader.nextInt();
String text=reader.nextLine();
actressLine(text, yearNumber, writer1);
String textt=reader.nextLine();
movieLine(textt, yearNumber, writer2);
}
writer1.close();
writer2.close();
}
public static void actressLine(String text, int year, PrintWriter writer) {
writer.println(year + text);
}
public static void movieLine(String text, int year, PrintWriter writer ) {
writer.println(year + " " + text);
}
}https://stackoverflow.com/questions/28816193
复制相似问题