FileWriter 自己是FileOutputStream的一个包装器,将使用默认的编码格式输出chars. FileWriter的构造函数有一个能够表示若是文件已存在,是否向文件中追加的参数。 html
FileWriter通常用来将连续的字符串输出到文件中, 要咱们本身调用flush方法才会将字符串写入文件中。 java
固然FileWriter和FileOutputStream均可以向文件中写入内容,后者更底层一些,前者倾向于字符串的输出。 api
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. oracle
FileWriter is a subclass of OutputStreamWriter class that is used to write text (as opposed to binary data) to a file. app
So if you want to handle binary data such as image file as in your case, you should be using FileOutputStream instead of FileWriter. ide
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. flex