1

我刚开始使用 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();


    }

}
4

1 回答 1

1

问题是对 java.io 包的一些调用会引发异常。

简单修复:将以下内容添加到您的方法签名中

 public static void main(String[] args) throws IOException 

几乎同样容易修复:添加 try/catch/finally 块。

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 = null;
    try {   
        out = new PrintWriter(
                new BufferedWriter(
                        new FileWriter(productFile)));      

        out.println("java\tMurach's Beginning Java 2\t$49.99");
    }
    catch(IOException ex) {
        // todo exception handling

        System.out.println("ERROR! " + ex);

    }
    finally {
        out.close();

    }

    BufferedReader in = null;
    try {
        in = new BufferedReader(
                new FileReader(productFile));

        String line = in.readLine();
        System.out.println(line);
    }
    catch (IOException ex) {
        // todo more exception handling
        System.out.println("ERROR! " + ex);
    }
    finally {
        in.close();
    }

}

编辑:你知道你要打out.close()两次电话吗?第二个应该是调用in.close()

于 2012-05-03T17:53:26.997 回答