FileWriter 本身是FileOutputStream的一个包装器,将使用默认的编码格式输出chars. FileWriter的构造函数有一个可以表示如果文件已存在,是否向文件中追加的参数。
FileWriter一般用来将连续的字符串输出到文件中, 要我们自己调用flush方法才会将字符串写入文件中。
当然FileWriter和FileOutputStream都可以向文件中写入内容,后者更底层一些,前者倾向于字符串的输出。
FileWriter is meant for writing streams of characters. It will use the default character encoding and the default byte-buffer size. In other words, it is a wrapper class of FileOutputStream for convenience. Therefore, to specify these values yourself, consider using a FileOutputStream.
FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file.
So if you want to handle binary data such as image file as in your case, you should be using FileOutputStream instead of FileWriter.
import java.io.FileWriter;
import java.io.Writer;
public class WriterTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Writer writer = new FileWriter("helloworld.txt");
String str = "hello test1";
writer.write(str);
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
类似的FileReader和FileInputStream也有类似的关系
Whether to use streams of bytes or characters? It really depends. Both have buffers. InputStream/OutputStream provide more flexibility, but will make your “simple” program complex. On the other hand, FileWriter/FileReader give a neat solution but you lose the control.