First of all, don't reinitialize the PrintStream object in every loop iteration.
To write to a file, simply call PrintStream's println method. You may not realise it, but when you print to the console, this is exactly what you are doing. System.out is a PrintStream object.
PrintStream out =
new PrintStream(new File("stuff.txt"));
while (in.hasNext()) {
String word = in.next();
out.println(convert(word));
}
Answer from Jade on Stack OverflowVideos
First of all, don't reinitialize the PrintStream object in every loop iteration.
To write to a file, simply call PrintStream's println method. You may not realise it, but when you print to the console, this is exactly what you are doing. System.out is a PrintStream object.
PrintStream out =
new PrintStream(new File("stuff.txt"));
while (in.hasNext()) {
String word = in.next();
out.println(convert(word));
}
import java.io.PrintStream;
public class Main2{
public static void main(String[]args){
String str = " The Big House is";
PrintStream ps = new PrintStream(System.out);
ps.printf("My name is : %s White", str);
ps.flush();
ps.close();
}
}
Output is : The Big House is White
The other way to use PrintStream is...
CharSequence cq = "The Big House is White";
PrintStream ps = new PrintStream(System.out);
ps.append(cq);
ps.flush();
ps.close();
}
}
If you want to use map:
Copyp.entrySet().stream()
.map(e -> " "+e.getKey()+" "+e.getValue())
.forEach(System.out::println);
Copyp.entrySet().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
or
Copyp.forEach((key, value) -> System.out.println(key + " " + value));
output = new PrintStream(System.out);
or actually,
output = System.out;
Similarly, you can do the same with System.err
... So why don't we just simply use System.out and System.err directly? sout + tab is quite fast to type in IntelliJ
System.out or System.error are already PrintStream and we can use them to print the output to command line without creating a new PrintStream object that you are doing.
Advantage of using this printStream is that you can use System.setOut() or System.setErr() to set the printSteam of your choice
PrintStream output = new PrintStream("./temp.txt");
System.setOut(output);
Above will override the default Printstream of printing to command line and now calling System.out.println() will print everything in given file(temp.txt)