Engineering Full Stack Apps with Java and JavaScript
Need to read input from Keyword using BufferedReader
BufferedReader cannot directly use an InputStream. Hence you need to also use an InputStreamReader which will act like a bridge between an InputStream like PrintStream and a Reader like BufferedReader.
import java.io.*;
public class FileCopier {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
FileWriter fw = new FileWriter("myFile.txt");
System.out.println("Enter text (enter string 'end' on a line to end):");
String str = "";
while (!str.equals("end")) {
str = br.readLine();
fw.write(str);
fw.write(System.lineSeparator());
}
fw.close();
br.close();
}
}
Using a BufferedWriter will still improve the code in terms of performance and also adds a convenience method newLine() which will print the line separator string as defined by the system property line.separator. You can attach a FileWriter to a BufferedWriter as:
BufferedWriter bw = new BufferedWriter(fw);
And then replace the line:
fw.write(System.lineSeparator());
with
bw.newLine();