除了直接将 Filename 传递给 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");