简体   繁体   中英

Doesn't create a txt file java

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

It's not creating the txt file in C: Btw this works fine in a mac using:

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

The following code works well for me

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

Result :

在此处输入图片说明

Don't forget to close your Stream after use, and this is best to do in a finally block, so that it is almost guaranteed to be done. Also, when you declare your out variable, set it initially to null so that the compiler will see that you do set it to something before using it. Do something like so:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM