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

时间:2023-03-09 10:02:08
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{
FileInputStream in = null;
FileOutputStream fs = null;
try {
//实例化文件,并判断文件是否存在
File oldfile=new File(oldpth);
if(oldfile.exists()){
//初始化文件输入与输出流
in=new FileInputStream(oldpth);
fs=new FileOutputStream(newpath,add);
//定义存放读取数据的数组
byte[] buffer=new byte[10];
int length;
while(true){
int len=in.read(buffer);//当文件读完,返回-1,否则返回读取文件长度
/*注:输出读取的当前文件内容方法
* String s=new String(buffer);
* s.trim();(去除字符串前后两端的空格)
*/
if(len==-1)break;
fs.write(buffer);
}
System.out.println("OK");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
in.close();
fs.close();
}
}
}

/**
* IO流的数据写入和读取
* 在本质上是用的FileReader("c:text.txt")或FileWriter("c:text2.txt")
* 通过read()或write()读取或写入单个字符存入数据中
* 由于操作起来比较麻烦效率不高。所以后来引入了缓冲流的概念,
* 所以出现了BufferedReader对象,通过这个对象,将fileRead读取的数据进行缓冲
* 提高效率
* */