读书人

java对资料拷贝的简单操作

发布时间: 2013-10-11 14:52:39 作者: rapoo

java对文件拷贝的简单操作

package fileInputStream;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;import javax.swing.JOptionPane;public class Test3 {/** * @param args *            实现功能: 将一个文件拷贝到指定路径中 */public static void copyFile(String url1, String url2) {// 获取指定的需要复制的文件File file1 = new File(url1);InputStream is = null;// 获取指定指向的复制路径File file2 = new File(url2);OutputStream os = null;File file3 = new File(file2, "2.txt");// 这里也可以对传入的路径进行一个判断,判断其是否有效,if (!file2.exists()) {System.out.println("路径不存在,是否进行创建");//提示用户int var = JOptionPane.showConfirmDialog(null, "指定文件路径不存在,是否将其创建??");if (var == 0) {file2.mkdirs();// 如果指定的路径不存在,那么就创建一个try {// 创建文件输入流的实体对象is = new FileInputStream(file1);// 创建文件输出流的实体对象os = new FileOutputStream(file3);// 创建缓冲区byte[] buffer = new byte[1024];// 创建判断实际读取长度的变量int len = 0;// 向缓冲区读入资源数据while ((len = is.read(buffer)) != -1) {// 从缓冲区向外输出资源数据os.write(buffer, 0, len);// flush() 是把缓冲区的数据强行输出os.flush();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (is != null) {try {// 关闭流资源is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (os != null) {try {// 关闭流资源?os.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}else{JOptionPane.showMessageDialog(null, "请重新选择路径!");}} else {try {// 创建文件输入流的实体对象is = new FileInputStream(file1);// 创建文件输出流的实体对象os = new FileOutputStream(file3);// 创建缓冲区byte[] buffer = new byte[1024];// 创建判断实际读取长度的变量int len = 0;// 向缓冲区读入资源数据while ((len = is.read(buffer)) != -1) {// 从缓冲区向外输出资源数据os.write(buffer, 0, len);// flush() 是把缓冲区的数据强行输出os.flush();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (is != null) {try {// 关闭流资源is.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (os != null) {try {// 关闭流资源?os.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}public static void main(String[] args) {// TODO Auto-generated method stub// 定义指定要拷贝的文件String url1 = "F:\\test\\1.txt";// 定义指定的拷贝位置即文件名String url2 = "F:\\test\\aa\\bb\\c\\d";// 调用拷贝文件的方法,copyFile(url1, url2);}}

读书人网 >编程

热点推荐