复制粘贴功能的实现
准备工作:创建一个文本文件a.txt,里面内容写入任意英文字母。
通过字节流实现对a.txt文档的复制粘贴功能。
(首先想一想复制粘贴功能是怎样的然后再去实现,其实就是a.txt文件中的内容写入到b.txt问中)
思路:
读取到a的内容
写入b中
注意的点:
¥应该循环读取数据,如果文件过大读不完
¥不用再创建一个b.txt文本文件,会自动创建
¥注意close()方法写到finally处,这样如果项目是异常退出文件也会关闭
这个代码只是初学写的,日后会有2.0版
public static void pasteCopy(String path1,String path2){
FileInputStream in=null ;//创建文件读取对象
FileOutputStream out=null;//创建文件写入对象
try {
in= new FileInputStream(path1);//更新in
out = new FileOutputStream(path2 , true);//更新out 使得out在本身有值的情况下也可以写入
byte []bytes =new byte[100];
//大文件读取 循环读取数据
int num=0;
while ((num =in .read(bytes ))!=-1 ){
System.out.println(new String(bytes ,0,num));//防止后面的数据存在问题
out .write(bytes ,0,num );//文件过大写入 循环写入
}
out .flush() ;//刷新此输出流并强制写出所有缓冲的输出字节
System.out.println("复制粘贴完成!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) { //多线程环境下
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close() ;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
String path1="C:\\Users\\Administrator\\Desktop\\a.txt";
String path2="C:\\Users\\Administrator\\Desktop\\b.txt";//会自动创建b.txt
pasteCopy(path1 ,path2 );
}