gpt4 book ai didi

java - 如何打印到文件?

转载 作者:行者123 更新时间:2023-12-04 05:49:31 25 4
gpt4 key购买 nike

我正在完成一项任务并且遇到了一些障碍。

我的程序将输出打印到屏幕上(不是我需要的),但只打印文件的第一个条目。下面是代码片段。该文件似乎正在从输入文件中读取数据,但循环不会在第一个条目之后输出到文件。

Scanner in = new Scanner(System.in);    //Scanner object to read input from the file
System.out.println("Enter filename to read "); //file name prompt
String inputFileName = in.nextLine(); //line input reads next line

/*
* TODO 2) Use an unbuffered file input stream to open listings.txt file
* and read in property listings.
*/
Scanner reader = null;
try {
reader = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {

System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
return;

}

PrintWriter out = new PrintWriter("agentreport.txt"); //This method prints out the file readfile.txt a word at a time
while (reader.hasNextLine()) { //It needs to output to the text file. Currently a file is created, but it is empty?
Scanner s2 = new Scanner(reader.next());

@SuppressWarnings("unused")
boolean b;
while (b = s2.hasNext()) {
String output = s2.next();
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2); //only printing the first entry to the agentsreport.txt file. Not stepping thru the file for some reason?
}

最佳答案

即使您正在使用自动刷新(在这种情况下不是这样),PrintWriter 对象也会在其内部缓冲区中输出任何内容,除非您执行以下两项操作之一:

1) 使用 println() , printf() , 或 format()方法

2) 调用flush()每次打印时方法,这样内部缓冲区中的所有数据都会被写出。

注意:print()方法不会导致 PrintWriter 对象为 flush()它的缓冲区。

尝试添加对 flush() 的调用在您调用 print() 之后

split() 示例

PrintWriter out = new PrintWriter("agentreport.txt"); 
while (reader.hasNextLine()) {
String words = reader.nextLine().split();

@SuppressWarnings("unused")
boolean b;
for(String word : words) {
String output = word ;
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2);
}

关于java - 如何打印到文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10250214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com