jake craigslist
jake craigslist

Reputation: 303

How to create an output file in java?

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.

Upvotes: 2

Views: 5429

Answers (2)

Michael Morgan
Michael Morgan

Reputation: 53

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

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35011

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

Upvotes: 3

Related Questions