2

I have all of my code in java setup, but how would I copy the console's output and have that go to a output.txt file? I have this code at top:

    Scanner console = new Scanner(System.in);
    System.out.print("Enter Input file name: ");
    String inputFileName = console.next();
    System.out.print("Output file: ");
    String outputFileName = console.next();
    File inputFile = new File(inputFileName);
    Scanner in = new Scanner(inputFile);
    PrintWriter out = new PrintWriter(outputFileName);

It prompts me to enter the input file (input.txt) and the output file (output.txt). When I enter all of my information it creates an output file, but nothing is written in it. I need what the console outputs to be written in the file.

1

2 Answers 2

3

Seems like you may be having a threading issue. You probably need to run the following in a new thread (as shown)

class myRunner implements Runnable {
  public void run() {
    while (true) {
      String ln = in.nextLine();
      out.println(ln);
    }
  }
}
new Thread(new myRunner()).start();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this helped. I didn't put in a out.println(). That's terrible a terrible mistake to miss.
2

Try something like this, you can output to the console and to the output file, your not really "copying".

System.out.println("whatever console output");

if (Files.notExists(outputFileName)) {
    try {
        File file = new File("output.txt");
            try (BufferedWriter output = new BufferedWriter(new FileWriter(file))) {
                output.write("console output, blah blah");
                output.newLine();                    
                output.close();
            }     
    } catch ( IOException e ) {}

You can store your console output as an array list and iterate over that to that output file as well

for(i = 0, i < ArrayList.length, i++) {
    output.write(i);
    output.newLine();
}
output.close();

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.