gpt4 book ai didi

java - 尝试显示创建的输出文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:45 28 4
gpt4 key购买 nike

所以我将一个文件传递给文件编写器,然后传递给打印编写器。然而,根据我的分配指令,我应该打印这些变量,我使用父类(super class)中的 toString 方法传递给 printwriter。这是一项作业,因此规则非常明确,说明教师希望输出如何。

 System.out.print("Please enter a file name: ");
fileName = input.next();
File fw = new File(fileName + ".txt");

AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);

System.out.println(acctException.toString()); <---This works


// pass object to printwriter and pw to write to the file
pw = new PrintWriter(fw);
// print to created file
pw.println(firstName);
pw.println(lastName);
pw.println(balance);
pw.println(id);
pw.println(RATE);
System.out.println(pw.toString()); <---Doesn't work. Only prints location and im supposed to somehow use the overloaded toString method to output the data within the file (i guess after its written)

最佳答案

你实际上已经给出了自己的解决方案,但你需要这样的东西 -

pw = new PrintWriter(fw);
try {
// print to created file
// pw.println(firstName);
// pw.println(lastName);
// pw.println(balance);
// pw.println(id);
// pw.println(RATE);
pw.println(acctException.toString()); // <-- Since
// System.out.println(acctException.toString()); works!
} finally {
pw.close(); // <-- Always close()!
}

关于java - 尝试显示创建的输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22902880/

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