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