1.建立联系 file对象
2.选择流:writer FileWriter
3.读取while(字符数组,0,长度)+flush
4.关闭资源
之前文件写出的时候,需要把String字符串转化成byte数组,才可以使用writer方法写出,
但是Writer提供了不同的writer方法,可以直接写出字符串,如下:
代码:
public class Demo05 { public static void main(String[] args) { /** * 纯文本写出 */ //1.获取File对象 File dest=new File("F:/Picture/test/test2.txt"); //2.选择流 Writer writer=null; try { //true代码追加文件,false代码覆盖,默认false覆盖 writer=new FileWriter(dest,true); String str="我们都是好孩子!"; //3.写出,强制刷出 writer.write(str); //可追加 writer.append("hahaahaha"); writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(writer!=null){ try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
字符流拷贝:
public class Demo05 { public static void main(String[] args) { /** * 纯文本的拷贝 */ File src=new File("F:/Picture/test/test.txt"); File dest=new File("F:/Picture/test/test3.txt"); Reader re=null; Writer wr=null; try { re=new FileReader(src); wr=new FileWriter(dest); char[] buffer=new char[1024]; int len=0; while(-1!=(len=re.read(buffer))){ wr.write(buffer); wr.flush(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (wr != null) { wr.close(); } if (re != null) { re.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }