不';不要用java创建txt文件

不';不要用java创建txt文件,java,file-io,Java,File Io,它不是在C中创建txt文件: 顺便说一句,这在mac中运行良好,使用: PrintStream out; try { out = new PrintStream(new FileOutputStream( "C:\\RandomWalkResultater.txt", true)); System.setOut(out); 如果要创建文件,请尝试使用新文件(“C:\\randomWalkResultator.txt”).createNewFile()。以下代码对我很有用 Print

它不是在C中创建txt文件: 顺便说一句,这在mac中运行良好,使用:

PrintStream out;
try {
   out = new PrintStream(new FileOutputStream( "C:\\RandomWalkResultater.txt", true));
   System.setOut(out);

如果要创建文件,请尝试使用
新文件(“C:\\randomWalkResultator.txt”).createNewFile()

以下代码对我很有用

PrintStream out;
try {
     out = new PrintStream(new FileOutputStream("/Volumes/DATA/Desktop/RandomWalkResultater.txt", true));
            System.setOut(out);
结果:


使用后不要忘记关闭流,最好在finally块中完成,这样几乎可以保证完成。另外,当您声明out变量时,首先将其设置为
null
,这样编译器会看到您在使用它之前确实将其设置为某个值。这样做:

final SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd.HH-mm" );
final String log = "C:/" + sdf.format( new Date());
System.setOut( new PrintStream( new FileOutputStream( log + "-out.txt" ), true ));
System.setErr( new PrintStream( new FileOutputStream( log + "-err.txt" ), true ));

完成后是否关闭流?@HovercraftFullOfEels不确定您的意思,因此可能不会:(在捕获后添加一个
finally{out.close();}
如果您没有得到任何异常或捕获到异常,这将关闭流。在任何情况下都很难关闭流,但操作系统会为我们这样做,当重定向到stdout和stderr时,这不是问题。@Templar如果我这样做,out。给出此错误“局部变量out可能尚未初始化”这是不现实的几个线程,一个GUI和可怜的旧遗留代码调用退出(x)的情况下,致命的错误。。。
  // declare your Stream variable and initialize to null
  PrintStream out = null; 
  try {
     // FILE_STREAM_PATH is a String constant to your output path
     out = new PrintStream(new FileOutputStream(FILE_STREAM_PATH, true));
     System.setOut(out);

     // use your Stream here

  } catch (FileNotFoundException e) {
     e.printStackTrace();
  } finally {
     // ***** close the Stream in the finally block *****
     if (out != null) {
        out.close();
     }
  }