不创建一个txt文件java

时间:2013-11-09 15:52:13

标签: java file-io

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

它不是在C中创建txt文件: 顺便说一句,这在mac中运行正常:

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

3 个答案:

答案 0 :(得分:0)

以下代码适用于我

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

结果:

enter image description here

答案 1 :(得分:0)

不要忘记在使用后关闭你的Stream,这最好在finally块中完成,这样几乎可以保证完成。此外,当您声明out变量时,最初将其设置为null,以便编译器在使用之前会看到您将其设置为某些。做类似的事情:

  // 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();
     }
  }

答案 2 :(得分:-1)

如果要创建文件,请尝试使用new File("C:\\RandomWalkResultater.txt").createNewFile()