尝试构造FileWriter时出错

时间:2013-11-16 23:16:15

标签: java filewriter

为什么这会给我一个错误?我很难过。

public void filewrite(String filename)
{   
    int lines = 10 + randomnumbers.nextInt(11);
    String randomnumber = Integer.toString(1 + randomnumbers.nextInt(11));

    FileWriter writer = new FileWriter(filename, true);
}

1 个答案:

答案 0 :(得分:1)

您正在使用的FileWriter构造函数被声明为抛出IOException。您需要catch或将您的方法声明为抛出它。

public void filewrite(String filename) throws IOException
{   
    int lines = 10 + randomnumbers.nextInt(11);
    String randomnumber = Integer.toString(1 + randomnumbers.nextInt(11));

    FileWriter writer = new FileWriter(filename, true);
    // use it
}

public void filewrite(String filename)
{   
    int lines = 10 + randomnumbers.nextInt(11);
    String randomnumber = Integer.toString(1 + randomnumbers.nextInt(11));

    try {
        FileWriter writer = new FileWriter(filename, true);
    } catch (IOException e) {
        // handle it
    }
}