写入多个文件而不复制代码Java

时间:2013-06-14 15:03:11

标签: java file-io

当我将用户添加到数组列表时,我将此代码写入文件。代码工作正常:

public void writeToFile(String content)
    {
        try {
            File file = new File("H:/JavaWorkspace/TradingPlatformProject/User_Report.txt");

            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content + "\n" );

            bw.close();
            logger.info("Recorded to User Activity file");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

当用户执行不同的操作时(例如,请求权限升级),我想写入单独的文件。有没有办法可以写入新文件“UserRequests.txt”而不复制此代码?

3 个答案:

答案 0 :(得分:7)

为什么不让方法更通用?

  public void writeToFile(String content, String fileName, String path)
  {
        try {
            File file = new File(path + fileName);

            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content + "\n" );

            bw.close();
            logger.info("Recorded to User Activity file");
        } catch (IOException e) {
            e.printStackTrace();
        }
  }

然后你可以使用该方法编写各种文件:3

答案 1 :(得分:1)

您应该只使用第二个参数,如下所示。 此外,你应该在finally块中关闭你的作家。这样,即使写入时发生异常,您也可以确保写入器已关闭。

public void writeToFile(String content, String path)
{
    FileWriter fw
    BufferedWriter bw 
    try {
        File file = new File(path);

        if (!file.exists()) {
            file.createNewFile();
        }
        fw = new FileWriter(file.getAbsoluteFile(), true);
        bw = new BufferedWriter(fw);
        bw.write(content + "\n" );

        bw.close();
        logger.info("Recorded to User Activity file");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        bw.close();
        fw.close();
    }
}

答案 2 :(得分:0)

我只会传入您要写入的文件:

public void writeToFile(String content, String filename){

然后:

File file = new File("H:/JavaWorkspace/TradingPlatformProject/"+filename);