输入流与输出流复制粘贴内容
一、复制粘贴 (使用字节流)可复制任何文件包括图片、文档等
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
//字节输入流
fis=new FileInputStream("C:/Users/Administrator/Desktop/test/bbb.txt");
//字节输出流(创建流对象时写入路径可以判断文件是否存在如没有新建一个文件)
fos=new FileOutputStream("C:/Users/Administrator/Desktop/test/ccc.txt");
byte b[]=new byte[1024];
int a=0;
while (true) {
a=fis.read(b);//每次循环读取1024字节
if (a==-1) {//读取不到就跳出循环。
break;
}
fos.write(b,0,a);//写入数据到文件(每次读取多少就写入多少)
}
fos.flush();//刷新
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (fis!=null) {
fis.close();//关闭输入流
}
if (fos!=null) {
fos.close();//关闭输出流
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
二、复制粘贴 (使用字符流)只能复制粘贴纯文本文件
public static void main(String[] args) {
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader("C:/Users/Administrator/Desktop/test/bbb.txt");
fw=new FileWriter("C:/Users/Administrator/Desktop/test/fff.txt");
char c[]=new char[20];
int a=0;
while (true) {
a=fr.read(c);
if (a==-1) {
break;
}
fw.write(c,0,a);
}
fw.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (fr!=null) {
fr.close();
}
if (fw!=null) {
fw.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
备注:
使用字符流只能复制粘贴纯文本文件(例如 .txt)。不能复制粘贴图片、音频、视频、word等文件。因为字符流就是字节流+编码表,而用字符流去复制图片时,字符流会默认将图片的字节码格式进行编码, 所以会导致复制后的图片与原图片可能不一致甚至会丢失数据。
所有我们在项目开发中读写文件尽量使用字节流。
文件都由字节组成