gpt4 book ai didi

java - 从文本文件读取并尝试使用 printWriter 写入另一个文件会导致空白文件

转载 作者:行者123 更新时间:2023-12-01 11:41:51 25 4
gpt4 key购买 nike

我的任务如下:

to write a program that reads the attached text file and writes out a separate text file (using your first initial and last name as the filename). The new text file should contain all the same lines of text as the input file with the addition of a line number appended as the first character on the line.

Ex: if your input line reads:

this is a test

your output should read

  1. this is a test

我已经编写了我认为主要是功能性的代码 - 在运行时它会编译并创建一个要写入的新文件,但该文件是空白的(包含 0 字节)。阅读问题后,我尝试确保我的 printWriter 和输入/输出流已关闭/刷新。我现在不确定我的循环是否有问题,或者我是否在错误的位置调用了 close 方法。如有任何帮助,我们将不胜感激。

代码如下:

package module6lecture;

import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ReadWriteProgram {

public static void main(String[] args) {
try
{
FileInputStream fis = new FileInputStream("C:\\Users\\Reid\\Desktop\\Chapter11.txt");
FileOutputStream fos = new FileOutputStream("C:\\Users\\Reid\\Desktop\\rulicny.txt");
Scanner scan = new Scanner(fis);
PrintWriter pw = new PrintWriter(fos);
int lineNumber = 1;
while(scan.hasNextLine());
{
String stringRead = scan.nextLine();
pw.println(lineNumber + ": " + stringRead);
lineNumber++;
}
pw.close();
}
catch(FileNotFoundException fnf)
{
System.out.println("Unable to find Chapter11.txt. Exiting...");
fnf.printStackTrace();
}
}
}

免责声明:我是个新手。

最佳答案

while 循环后面有分号

while(scan.hasNextLine());
// ^

这使得它无限循环,因为它代表空指令,就像

while(scan.hasNextLine()){}

所以你永远不会真正进入

{
String stringRead = scan.nextLine();
pw.println(lineNumber + ": " + stringRead);
lineNumber++;
}

block ,以及其后的代码,这意味着您没有向结果文件写入任何内容,甚至没有关闭它。如果使用

创建空文件,则您拥有的全部内容
FileOutputStream fos = new FileOutputStream("C:\\Users\\Reid\\Desktop\\rulicny.txt");

所以删除这个分号。

<小时/>

顺便说一句,如果您让 IDE 为您格式化代码,您可以轻松发现此类错误。 Eclipse 将您的示例格式化为

while (scan.hasNextLine())
;
{
String stringRead = scan.nextLine();
pw.println(lineNumber + ": " + stringRead);
lineNumber++;
}
正如您所看到的,这很好地表明您的循环实际上执行空语句而不是代码块。

关于java - 从文本文件读取并尝试使用 printWriter 写入另一个文件会导致空白文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29462921/

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