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

标签 java eclipse run-configuration

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

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 中的“运行配置”->“通用”->“输出文件”,但这对我没有帮助。

最佳答案

您需要向其传递一个 File 实例,而不是直接将 Filename 传递给 FileOutputStream:

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");

关于java - 如何设置System.setOut()的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48184590/

相关文章:

java | JavaBean监控

python - Django + Eclipse,外壳问题

node.js - 为什么此 WebStorm 配置不允许我在 Node 应用程序中命中断点?

c - Eclipse CDT - 共享库依赖问题

java - 如何使用 Eclipse 创建通用启动配置?

eclipse - 找不到 Eclipse 路径变量中的批处理文件

java - 单击按钮时出现 NullPointerException

java - JTextPane 中的 log4j

java - addCookie 方法不会将 cookie 添加到 httpServletResponse

java - 应用 SRP 和 OCP