I am trying to get the output of my java program to write to a file.
The user inputs some data which should not be included in the file. When the program responds it should output information to the user, as well as write SOLELY the output to a file.
From examples I have begun with this at the top of my driver class:
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;
This code is in every place where I might receive output from the program:
try {
lineFromInput = in.readLine();
FileWrite.write(lineFromInput);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And the class its calling is:
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
}
It creates the output file, but thats it. None of the output from the program is written.
I’ve looked over numerous examples and this seems to be the easiest way to get the ball rolling, although I’m open to any other suggestions.
Thanks!
I think it should be
InputStremReaderwith singletin statement below:As
EDIT: This works fine. Please make sure you provide the input through input console. Also please note that it reads and write(overwrite) single line ONLY.
EDIT 2: Updated program for multi-line inputs. Its not best way to open and close file each time to write, but I am just trying to make your program work with minor changes. Let me know, if you need suggestion to avoid repeated opening/closing of the output file.
Change Highlights:
Open the file in
appendmode.EDIT3: Your updated program using
Scannerto read the inputs: