java写文件读写操作(IO流,字符流)



package copyfile; import java.io.*; public class copy { public static void main(String[] args) throws IOException { copyFile("d:/new/a.txt","d:/new/b.txt",true);//oldpath,newpath,是否不覆盖前文 } public static void copyFile(String oldpth,String newpath,boolean add) throws IOException{ FileReader fr = null; FileWriter fw = null; try { //实例化文件,并判断文件是否存在 File oldfile=new File(oldpth); if(oldfile.exists()){ //初始化文件输入与输出流 fr=new FileReader(oldpth); fw=new FileWriter(newpath,add); //定义存放读取数据的数组 char[] buffer=new char[10]; int length; while(true){ int len=fr.read(buffer);//当文件读完,返回-1,否则返回读取文件长度 if(len==-1)break; fw.write(buffer); } System.out.println("OK"); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ fr.close(); fw.close(); } } }

  

原文地址:https://www.cnblogs.com/zxxiaoxia/p/4166026.html