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.

3
  • Don't use a system out , rather just write to a file .. stackoverflow.com/questions/15758685/… Commented May 5, 2014 at 17:54
  • 1
    This may serve your needs stackoverflow.com/questions/16237546/… Commented May 5, 2014 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 Commented May 5, 2014 at 18:36

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
You will need to call the flush() method on the FileWriter which writes the content of the buffer to the destination file.
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();
    }
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.