1

I know that this type of question have been asked many times. But I didn't find any answer for myself. That's why i am asking once more.

I have got an output on my console. I want to copy the same output 1-to-1 to a file. I don't want to redirect. I want some kind of "copy" it and "write" into a file. I hope the question is clear enough, cause I have seen that the other times, the question wasn't clear.

Anyways, I have tried it with the "System.setOut" methode. But it just redirect everything to the file. I cannot write all the "System.out.println"s with a write() into a file, that to much.

Thanks for helping.

  • Don't use a system out , rather just write to a file .. http://stackoverflow.com/questions/15758685/how-to-write-logs-in-text-file-when-using-java-util-logging-logger – Kenneth Clark May 05 '14 at 17:54
  • 1
    This may serve your needs http://stackoverflow.com/questions/16237546/writing-to-console-and-text-file – Kenneth Clark May 05 '14 at 17:59
  • Thanx! @Kenneth: I had alread found that. But the problem here was, it just went through my while and for loops and wrote and in the file the last output. I guess it overwrote just the others – user3578544 May 05 '14 at 18:36

2 Answers2

0

There is no way you can get console output. You have to do everything before printing

To Write our to a file do this.

try{

FileWriter x = new FileWriter(new File("x.txt"));
x.write("hello");

}catch(IOExecption e){

}

That will write out hello to a file

rush2sk8
  • 362
  • 6
  • 16
  • but how can I do it? i got this one: FileOutputStream myFile = new FileOutputStream(task.getResultFile()); PrintStream output = new PrintStream(in); then everytime i called System.out.println(), I also called output.println(). But the problem was as i said to Kenneth, that it overwrite all the other lines and print in the file, only the last phrase, since i am using while and for loops. – user3578544 May 05 '14 at 18:46
  • 1
    You will need to call the `flush()` method on the FileWriter which writes the content of the buffer to the destination file. – Kenneth Clark May 06 '14 at 04:39
0

You could do something like this , the system out will happen after the log to file. This code will append. Please This is NOT a good example of Exception handling, just an example of what you can do.

  protected void writeToFileAndLog(String logEntry)
  {
    String file = "MyAmazingLog.txt";
    try
    {

      FileOutputStream appendedFile = new FileOutputStream(file, true);
      DataOutputStream out = new DataOutputStream(appendedFile);

      out.writeBytes(String.format("%s\n", logEntry));
      out.flush();
      out.close();
      System.out.println(logEntry);
    }
    catch (FileNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }
  }
Kenneth Clark
  • 1,725
  • 2
  • 14
  • 26