I do not understand why it is not writing to the file while it is writing to the console. Where do I go wrong?
package com.codegym.task.task19.task1917;
/*
Your own FileWriter
*/
import java.io.*;
public class FileConsoleWriter {
//1. The FileConsoleWriter class must contain a private FileWriter field called fileWriter that should not be initialized immediately.
private FileWriter fileWriter;
//2. The FileConsoleWriter class must have five constructors that initialize the fileWriter for writing.
public FileConsoleWriter(FileDescriptor fileDescriptor) throws IOException {
fileWriter = new FileWriter(fileDescriptor);
}
public FileConsoleWriter(String s) throws IOException {
fileWriter = new FileWriter(s);
}
public FileConsoleWriter(File file) throws IOException {
fileWriter = new FileWriter(file);
}
public FileConsoleWriter(String s, boolean append) throws IOException {
fileWriter = new FileWriter(s, append);
}
public FileConsoleWriter(File file, boolean append) throws IOException {
fileWriter = new FileWriter(file, append);
}
//3. The FileConsoleWriter class must have a write(char[] cbuf, int off, int len) throws IOException method,
// which should write data to fileWriter as well as the console.
public void write(char[] cbuf, int off, int len) throws IOException {
fileWriter.write(cbuf, off, len);
System.out.print(new String(cbuf).substring(off, off + len));
}
public void write(int c) throws IOException {
fileWriter.write(c);
System.out.println((char) c);
}
//FileWriter can write entire Strings
public void write(String str) throws IOException {
fileWriter.write(str);
System.out.println(str);
}
public void write(String str, int off, int len) throws IOException {
fileWriter.write(str, off, len);
System.out.println(str.substring(off, off + len));
}
public void write(char[] cbuf) throws IOException {
fileWriter.write(cbuf);
for (int i = 0; i < cbuf.length; i++) {
System.out.print(cbuf[i]);
}
}
public void close() throws IOException {
fileWriter.close();
}
public static void main(String[] args) throws IOException {
FileConsoleWriter fw = new FileConsoleWriter("/Users/lilianetop/Desktop/taak1917.txt");
fw.write("Liliane is playing with the FileWriter");//why is this not added to the file?
char[] buffer = new char[6];
buffer[0] = 'l';
buffer[1] = 'i';
buffer[2] = 'l';
buffer[3] = 'a';
buffer[4] = 'n';
buffer[5] = 'e';
fw.write(buffer);
FileReader fr = new FileReader("/Users/lilianetop/Desktop/taak1917.txt");//returns empty
System.out.println();
while (fr.ready()) {
System.out.print((char) fr.read());//output is byte so needs to be cast to char
}
}
}