代码之家  ›  专栏  ›  技术社区  ›  Spider

如何设置系统的目录。放样()

  •  2
  • Spider  · 技术社区  · 8 年前

    我想将输出另存为指定文件夹中的一个单独文件。以下代码将在项目根目录下保存输出。我怎样才能改变它?

    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中的“输出文件”,但它对我没有帮助。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Emax    8 年前

    不必直接将文件名传递给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");
    
    推荐文章