C
C
cot0322016-01-11 12:57:12
Java
cot032, 2016-01-11 12:57:12

How to write console output to a file?

How to write console output from a class to a file?
There is a class
public class Game implements {
public static void main(String[] args) {
Field field = new Field();
GameObject player = new Player();
field.addObject(player);
for (int i = 0; i < 10; i++) {
field.moveAll();
Thread.sleep(10);
}
It outputs
player moved to (8,6)
player moved to (9,6)
player moved to
(16,11) player moved to (19,13)
player moved to (21,13)
player moved to (21,12 ) )
player moved to (24,11)
player moved to (29,14)
player moved to (34,20)
player moved to (42,26)
How do I write this to a file?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evhen, 2016-01-11
@EugeneP2

The easiest option is in the console when you run your program
or
The second option, also simple, is to override System.out

static {
    try {
      System.setOut(new PrintStream(new File("file.txt")));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws FileNotFoundException {

    System.out.println("Hello World!"); // будет записано в файл
  }

V
Vitaly Shkurenko, 2016-01-11
@stuf4ik

How to create a file and write to a file in Java? (SO)

C
cot032, 2016-01-11
@cot032

It seemed to me that objects are displayed on the console and you need to either write them as objects to a file or as strings, so that you can then output
out.println is contained only in the Field class method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question