我刚开始使用 Murach 的 Se 6 中的示例进行文件 I/O 和im。这是我的代码。我是不是错过了什么。我知道后面的代码还有更多,但因为这是一个例子,这应该可以正常工作吗?
//Import import java.io.*; for use with the File I/O Methods.
import java.io.*;
public class MainApp
{
public static void main(String[] args)
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}
//回答
通过在我初始化主代码的末尾添加一个 throws 异常。甚至 txt 文件 products.txt 也像预期的那样在类文件夹中。//导入导入java.io.*; 用于文件 I/O 方法。
import java.io.*;
public class MainApp
{
public static void main(String[] args) throws Exception
{
//Create a file object.
File productFile = new File("product.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productFile)));
out.println("java\tMurach's Beginning Java 2\t$49.99");
out.close();
BufferedReader in = new BufferedReader(
new FileReader(productFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
}