如何设置 System.setOut() 的目录

how to set directory of the System.setOut()

我想将输出单独保存在指定文件夹中。以下代码会将输出保存在项目根目录中。我该如何更改它?

public static void main(String[] args) throws Exception {
      FileOutputStream f = new FileOutputStream("file.txt");
      System.setOut(new PrintStream(f));
      System.out.println("This is System class!!!");
}

此外,我曾尝试在 Eclipse 中更改 "Run Configurations"-> "Common"-> "Output File",但它对我没有帮助。

不是直接将文件名传递给 FileOutputStream,而是需要像这样传递一个 File 实例:

File directoryLogs = new File("logs");
fileDirectory.mkdirs(); // Create the directory (if not exist)

File fileLog = new File(directoryLogs, "log.txt");
fileLog.createNewFile(); // Create the file (if not exist)

然后

 public static void main(String[] args) throws Exception {

    // Create a log directory
    File directoryLogs = new File("logs");
    fileDirectory.mkdirs();

    // Create a log file
    File fileLog = new File(directoryLogs, "log.txt");
    fileLog.createNewFile();

    // Create a stream to to the log file
    FileOutputStream f = new FileOutputStream(fileLog);

    System.setOut(new PrintStream(f));
    System.out.println("This is System class!!!");

    // You should close the stream when the programs end
    f.close();
}

如果你想完全改变日志目录的路径你也可以指定 这里的绝对路径

// NB: Writing directly to C:\ require admin permission
File directoryLogs = new File("C:\MyApplication\logs");