Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how to redirect console output to file using java

807589Aug 12 2008 — edited Aug 13 2008
* how to redirect console output to file using java
* I have tried google,but i didnt get the useful link........
* the following is my code in that , console print the output successfully, but its not create th file with the console output....
import java.io.FileInputStream;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class ReadConsole {

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

		try {
			FileInputStream f = new FileInputStream(new File("D:/read.txt"));

			while (f.available() != 0) {
				System.out.print((char) f.read());
			}

			// create a buffered reader that connects to the console, we use it
			// so we can read lines
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));

			// read a line from the console
			String lineFromInput = in.readLine();

			// create an print writer for writing to a file
			PrintWriter out = new PrintWriter(new FileWriter("D:/output.txt"));

			out.println(lineFromInput);

			out.close();
		} catch (IOException e) {
			System.out.println("Error during reading/writing");
		}

	}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 10 2008
Added on Aug 12 2008
8 comments
8,352 views