OutputStream和Writer也很类似,其中Writer是以字节作为数据传输单位,允许使用String作为参数。
public class FileOutputTest { public static void main(String[] args) { try (FileInputStream in = new FileInputStream( "src/inputandoutput/FileOutputTest.java"); FileOutputStream out = new FileOutputStream("newFile.txt")) { byte[] buff = new byte[1024]; int hasRead = 0; while ((hasRead = in.read(buff)) > 0) { out.write(buff, 0, hasRead); } } catch (IOException e) { e.printStackTrace(); } } }
如果想要直接输出字符串的内容,使用Writer会有更好的效果。
public class FileWriterTest { public static void main(String[] args) { try (FileWriter fw = new FileWriter("fw.txt")) { fw.write("我是鸭鸭\r\n"); fw.write("I can fly!"); } catch (IOException e) { e.printStackTrace(); } } }