文件拷贝实例:
利用文件输入输出流编写一个实现文件拷贝的程序, 源文件名和目标文件名通过控制台输入。
public class Copy {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入您要拷贝的源文件:");
String str = sc.next();
System.out.print("请输入您要拷贝的目标文件:");
String s = sc.next();
/*
* 方法一:
* try {
FileInputStream fis = new FileInputStream(str);
byte[] b=new byte[fis.available()];
fis.read(b);
System.out.println("源文件内容:");
System.out.println(new String(b));
fis.close();
try {
FileOutputStream fos = new FileOutputStream(s);
String st = new String(b);
fos.write(st.getBytes());
fos.flush();
fos.close();
System.out.println("文件拷贝成功!");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
System.out.println("源文件未找到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//方法二:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(str);
fos = new FileOutputStream(s);
byte[] b = new byte[fis.available()];
while (fis.read(b)!=-1) {
fos.write(b);
}
System.out.println("文件拷贝成功!");
} catch (FileNotFoundException e) {
System.out.println("源文件未找到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(fis != null){
fis.close();
}
if(fos != null){
fos.flush();
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
图片拷贝实例:
将图片根据原路径拷贝到另一个路径内
public class PictureCopy {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("E:/iodemo/99.jpg");
fos = new FileOutputStream("E:/iodemo/00.jpg");
byte [] b = new byte[fis.available()];
while (fis.read(b)!=-1) {
fos.write(b);
}
fos.close();
System.out.println("图片拷贝成功!");
} catch (FileNotFoundException e) {
System.out.println("源文件未找到!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//finally关键字:无论出不出现异常最后都要执行finally语句中的代码
//最后再关闭流
try {
if(fis!=null){
fis.close();
}
if(fos != null){
fos.flush();
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}