Reputation: 324
I'm trying to send the output of my program to a text file called results.txt . Here's my attempt
public void writeFile(){
try{
PrintStream r = new PrintStream(new File("Results.txt"));
PrintStream console = System.out;
System.setOut(r);
} catch (FileNotFoundException e){
System.out.println("Cannot write to file");
}
But everytime I run the code and open the file the file is blank. This is what i want to output:
public void characterCount (){
int l = all.length();
int c,i;
char ch,cs;
for (cs = 'a';cs <='z';cs++){
c = 0;
for (i = 0; i < l; i++){
ch = all.charAt(i);
if (cs == ch){
c++;
}
}
if (c!=0){
//THIS LINE IS WHAT I'M TRYING TO PRINT
System.out.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
}
}
}
Where am I going wrong that it keeps creating the file but not writing to it? (Btw i do have a main method)
Upvotes: 0
Views: 1496
Reputation: 8693
As you found, System.out
IS-A PrintStream
and you can create a PrintStream
, passing it a File
to have it write to that file. This is the beauty of polymorphism --- your code writes to a PrintStream
and it doesn't matter what kind it is: console, file, even network connection, or zipped encypted network file.
So instead of messing with System.setOut
(usually a bad idea, as it may have unintended side effects; do this only if you absolutely have to (e.g., in some tests)), just pass the PrintStream
of your choice to your code:
public void characterCount (PrintStream writeTo) {
// (your code goes here)
writeTo.println("The character"+ " "+ cs + " "+ "appears --> "+" "+c+" "+ "times");
// (rest of your code)
}
Then you call your method as you want:
public static void main(String[] args) throws FileNotFoundException {
new YourClass().characterCount(System.out);
new YourClass().characterCount(new PrintStream(new File("Results.txt")));
}
(Note that I declared that main
may throw a FileNotFoundException
, as new File("...")
can throw that. When that happens, the program will exit with an error message and stack trace. You could also handle it like you did before in writeFile
.)
Upvotes: 1
Reputation: 21
use:
PrintWriter writer = new PrintWriter("Results.txt");
writer.print("something something");
don't forget to add:
writer.close();
when you are done!
Upvotes: 1
Reputation: 1187
JAVADOC: "A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently."
PrintStream can be used to write to an OutputStream, not directly to a file. So you can use PrintStream to write to a FileOutputStream and then write to the file with that.
If you just want to simply write to a file though, you can use Cans answer easily!
Upvotes: 0