javaIo文件中添加内容追加String

来源:互联网 发布:知乎win10显示不了桌面 编辑:程序博客网 时间:2024/06/05 15:02
StringBuilder b= new StringBuilder();
package week4HomeWork;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class Test {public static void main(String[] args) {File f1= new File("F:\\testio\\a\\a.txt");File f2= new File("F:\\testio\\c\\a.txt");Test.copy(f1,f2);}public static void copy(File f1,File f2){if(!f1.exists()){System.out.println("没有找到文件");}InputStream is =null;OutputStream os =null;try {is=new FileInputStream(f1);os=new FileOutputStream(f2);byte[] b= new byte[1024];int len=0;String strRead="";while((len=is.read(b))!=-1){ strRead=new String(b);}String str= "要添加的字符串";byte[] b1=str.getBytes();if(strRead!=null&&str!=null){if(!(strRead.equals(str))){StringBuilder sb=new StringBuilder();sb.append(str);sb.append(strRead);String str2=sb.toString();byte[] b2=str2.getBytes();os.write(b2);}}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally{try {is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}try {os.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}

0 0