将d:下面的一个文件夹下的文件全部拷贝的另外一个文件夹下面,然后在将这些文件打个zip的包这个没有写出来

解决方案 »

  1.   

    楼主,我今天上午刚学io,费了九牛2虎之力查api,实现了前半部分,zip没弄出来(文件夹里只能装文件,不能装文件夹,windows下,linux应该要改个小地方,比较混乱)import java.io.*;
    import java.util.zip.*;public class TestCopy
    {
    public static void main(String[] args)
    {
    String name1 = "E:\\zhangbk\\zhang\\src\\com";//源目录
    String name2 ="F:\\tt";                       //要复制目录
    CopyToRar test = new CopyToRar(name1,name2);
    try
    {
    test.copyWhole();
    }
    catch (IOException e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    class CopyToRar
    {
    private String nameSrc;
    private String nameDes;
    private File[] fileSrc;
    private String[] nameSrcArr;
    private String[] nameDesArr;
    private int length;
    CopyToRar(String nameSrc,String nameDes)
    {
    this.nameSrc = nameSrc;
    this.nameDes = nameDes;
    File src = new File(nameSrc);
    fileSrc = src.listFiles();
    length = fileSrc.length;
    String[] nameArr= new String[length];
    nameSrcArr = new String[length];
    nameDesArr = new String[length];
    for(int i=0;i<length;i++)
    {
    nameArr[i]=fileSrc[i].getName();
    nameSrcArr[i]=nameSrc+"\\"+nameArr[i];
    nameDesArr[i]=nameDes+"\\"+nameArr[i];
    }
    }
    public void copyWhole() throws IOException
    {
    File des = new File(nameDes);
    des.mkdir();
    String[] nameTemp = new String[length];

    for(int i=0;i<length;i++)
    {
    copy(nameSrcArr[i],nameDesArr[i]);
    }
    ZipEntry temp = new ZipEntry(nameDes);
    }
    public static void copy(String src,String des) throws IOException
    {
    FileInputStream fis = new FileInputStream(src);
    DataInputStream dis = new DataInputStream(fis);
    FileOutputStream fos = new FileOutputStream(des);
    DataOutputStream dos = new DataOutputStream(fos);
    int temp;
    while((temp=dis.read())!=-1)
    {
    dos.write(temp);
    }
    dos.close();
    fos.close();
    dis.close();
    fis.close();
    }
    public void changeToZip()
    {

    }

    }
      

  2.   

    楼上效率太低了,用renameTo方法,这样
    File oldfile = new File("yourOldFilePath");

    oldfile.renameTo(new File("yourNewFilePath"));
    (但这个函数有一个缺陷是:移位目标文件夹要在原文件夹下面)
    期待更完美的解答。。
      

  3.   

    renameTo似乎不行吧,在我机器上,它的功能就只是移动文件~
    java文件IO的API中,应该会有拷贝操作的吧(我没找到)....
      

  4.   

    renameTo 到别的文件夹就成了剪切了 那就不叫copy了
      

  5.   

    /**
     * 文件移动
     * @param srcFileName  原文件名称(含路径)
     * @param destFileName 目标文件名称(含路径)
     * @param isCover      是否覆盖同名文件
     * @return
     */
    public static boolean fileMove(String srcFileName, String destFileName,
    boolean isCover){
    boolean rt = true;
    File f = new File(srcFileName);
    File f2 = new File(destFileName);
    if (f2.exists()) {
    // 如果同意覆盖则删除原来文件,否则返回false
    if (isCover)
    f2.delete();
    else
    return false;
    }
    if(!f.renameTo(f2)) {
    rt = false;
    }
    return rt;
    }
      

  6.   


    /**
     * 文件移动
     * @param srcFileName  原文件名称(含路径)
     * @param destFileName 目标文件名称(含路径)
     * @param isCover      是否覆盖同名文件
     * @return
     */
    public static boolean fileMove(String srcFileName, String destFileName,
    boolean isCover){
    boolean rt = true;
    File f = new File(srcFileName);
    File f2 = new File(destFileName);
    if (f2.exists()) {
    // 如果同意覆盖则删除原来文件,否则返回false
    if (isCover)
    f2.delete();
    else
    return false;
    }
    if(!f.renameTo(f2)) {
    rt = false;
    }
    return rt;
    }
      

  7.   

    这个应该是拷贝         /**
     * 文件复制
     * @param srcFileName  原文件名称(含路径)
     * @param destFileName 目标文件名称(含路径)
     * @param isCover      是否覆盖同名文件  
     * @return
     */ public static boolean fileCopy(String srcFileName, String destFileName,boolean isCover){
    boolean rt = true;
    FileInputStream in;
    try {
    // 读取原文本文件
    in = new FileInputStream(srcFileName);
    byte[] indata;
    indata = new byte[in.available()];
    in.read(indata);
    in.close();
    // delete下用户文件夹如果不存在,则创建,目标文件不过不存在,则创建
    File f = new File(destFileName);
    if (!f.exists())
    f.createNewFile();
    FileOutputStream out;
    out = new FileOutputStream(destFileName);
    out.write(indata);
    out.close();
    } catch (FileNotFoundException e) {
    rt = false;
    ExceptionUtil.saveError(ErrorObject.BUSINESSERROR, "文本文件不存在",
    new Exception(e.getMessage()));
    e.printStackTrace();
    } catch (IOException e) {
    rt = false;
    ExceptionUtil.saveError(ErrorObject.BUSINESSERROR, "读取文本文件出错",
    new Exception(e.getMessage()));
    e.printStackTrace();
    }
    return rt; }
      

  8.   

    写两个方法
    void copyFile(File sources, File destDir);//递归调用
    void writeFile(File originalFile, File destDir);//产生新的文件大概内容
    void writeFile(File originalFile, File destDir) {
      //检查 originalFile为非空的文件(不是目录)
      // destDir应该是目录(复制到同名文件,因此不自带文件名了)
      // 否则抛出错误信息  // 检查destDir是否存在,不存在则创建目录
      // 创建目录失败检查destDir上级目录是否存在
      // 父目录不存在则抛出错误(调用本方法前应保证父目录已存在)
      
      // 在destDir下创建同名文件,读写文件完成复制
    }void copyFile(File sources, File destDir) {
      // 检查sources非空且存在、destDir非空
      // 检查destDir存在,不存在则创建目录(这里可能要注意下,如何保证创建成功楼主可以自己尝试下)
      // 如果source是文件而不是目录,直接调用writeFile
      // 否则,遍历source下的每个自文件,并对各个自文件调用本方法
      // 同时要注意,调用copyFile是 sources 和 destDir的目录层次要保持一致
    }
      
      

  9.   

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    //如果是windows下,将D:\srcroot目录里文件全部拷贝到D:\decroot中
    //如果是windows下,将D:/srcroot目录里文件全部拷贝到D:/decroot中
    public class Copy {
    static List scrList=new ArrayList();
    static List decList=new ArrayList();
    static int howmany=0; public static void main(String[] args) {
    String srcDir="D:"+File.separator+"srcroot";
    String decDir="D:"+File.separator+"decroot";
    int howmanyfiles=checkagain(srcDir,decDir);
    for(int i=0;i<howmanyfiles;i++){
    fileCopy(scrList.get(i).toString(),decList.get(i).toString(),true);
    }
    }

    static int checkagain(String srcDir,String decDir){
    File filedir=new File(srcDir);
    File file[]=filedir.listFiles();
    for(int i=0; i<file.length;i++){
    if(file[i].isFile()){
    scrList.add(srcDir+File.separator+file[i].getName());
    decList.add(decDir+File.separator+file[i].getName());
    howmany++;
    }else if(file[i].isDirectory()){
    checkagain(srcDir+File.separator+file[i].getName(),decDir+File.separator+file[i].getName());
    }
    }
    return howmany;
    }
    public static boolean fileCopy(String srcFileName, String destFileName,boolean isCover){
    boolean rt = true;
    FileInputStream in;
    try {
    // 读取原文本文件
    in = new FileInputStream(srcFileName);
    byte[] indata;
    indata = new byte[in.available()];
    in.read(indata);
    in.close();
    // delete下用户文件夹如果不存在,则创建,目标文件不过不存在,则创建
    File f = new File(destFileName);
    File parent = new File(f.getParent());
    if(!parent.isDirectory()){
    parent.mkdirs();
    }
    if (!f.exists())
    f.createNewFile();
    FileOutputStream out;
    out = new FileOutputStream(destFileName);
    out.write(indata);
    out.close();
    } catch (FileNotFoundException e) {
    rt = false;
    e.printStackTrace();
    } catch (IOException e) {
    rt = false;
    e.printStackTrace();
    }
    return rt; }
    }
      

  10.   

    采用通道复制文件,可以简捷一点import java.io.*;
    import java.nio.channels.*;
    public static void CopyFile(String src, String dst) throws IOException {
    FileChannel in = new FileInputStream(src).getChannel();
    FileChannel out = new FileOutputStream(dst).getChannel();
    in.transferTo(0, in.size(), out);
    in.close();
    out.close();
    }
      

  11.   

    package om.fileupload.zhangc;import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;public class DirCopy {

    public static void main(String[] args)throws Exception{
    dirZipCopy("d:/source","d:/source.zip");
    }
    /**
     * 文件夹压缩备份
     * @param fromDir 要压缩备份的文件夹
     * @param toDir 压缩至的路径
     * @throws Exception
     */
    public static void dirZipCopy(String fromDir,String toDir)throws Exception{
    //创建ZIP输出流
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(toDir));
    //递归处理文件夹
    zipCopy(new File(fromDir), zos, "");
    zos.close();
    }
    /**
     * 压缩复制文件
     * @param fromDir 要压缩的文件
     * @param zos ZIP输出流
     * @param path 相对于ZIP文件的路径
     * @throws Exception
     */
    private static void zipCopy(File fromDir,ZipOutputStream zos,String path)throws Exception{
    if(fromDir.exists()){
    if(fromDir.isDirectory()){
    path += fromDir.getName() + "/";
    zos.putNextEntry(new ZipEntry(path) );
    File[] files = fromDir.listFiles();
    if(files != null){
    for(int i = 0 ; i < files.length ; i ++ ){
    zipCopy(files[i],zos, path);
    }
    }
    }else{
    zos.putNextEntry(new ZipEntry(path + fromDir.getName()));
    InputStream is = new FileInputStream(fromDir);
    int len = 0 ;
    byte[] b = new byte[1024];
    while( (len = is.read(b)) != -1){
    zos.write(b, 0, len);
    zos.flush();
    }
    is.close();
    }
    }
    }
    }
      

  12.   

      java.util.zip貌似不支持中文啊
      

  13.   

    15楼的程序结构写得很好,要是把:
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    变成ant.jar包中的import org.apache.tools.zip.*;就perfect了
      

  14.   

    发现一个问题,就是十五楼的程序运行不能在源文件和目标文件在同一文件夹下
    会导致压缩一个空的文件的问题
    这是由于
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(toDir));
    这一句在进行目录压缩前会先生成一个空文件可以用如下方法解决:
    将main方法里面的内容用如下代替
    接受两个参数:第一个是文件夹,第二个是目标文件dirZipCopy(args[0], System.getProperty("java.io.tmpdir") + "/output.zip");
    new File(System.getProperty("java.io.tmpdir") + "/output.zip").renameTo(new File(args[1]));
      

  15.   


    import java.io.*;public class DealFile {
    /** 输入文件 */
    String infile = ""; /** 输出文件 */
    String outfile = ""; /** 输入文件流 */
    FileInputStream fis = null; /** 输出文件流 */
    FileOutputStream fos = null; public DealFile() {
    } /**
     * 建立输入文件流, 通过参数中指定的文件路径 fis = new FileInputStream(infile);
     */
    public void connFIS(String i) {
    try {
    infile = i;
    fis = new FileInputStream(infile);
    } catch (IOException ioe) {
    System.out.println("调用DealFile.connFIS()函数错误:\r\n" + ioe);
    }
    } /**
     * 建立输出文件流,通过参数中指定的文件路径 fis = new FileInputStream(outfile);
     */
    public void connFOS(String o) {
    try {
    outfile = o;
    fos = new FileOutputStream(outfile);
    } catch (IOException ioe) {
    System.out.println("调用DealFile.connFOS()函数错误:\r\n" + ioe);
    }
    } /**
     * 关闭输入文件流
     */
    public void closeFIS() {
    try {
    if (fis != null) {
    fis.close();
    }
    } catch (IOException ioe) {
    System.out.println("调用DealFile.closeFIS()函数错误:\r\n" + ioe);
    }
    } /**
     * 关闭输出文件流
     */
    public void closeFOS() {
    try {
    if (fos != null) {
    fos.close();
    }
    } catch (IOException ioe) {
    System.out.println("调用DealFile.closeFOS()函数错误:\r\n" + ioe);
    }
    } /**
     * 取得输入流
     */
    public FileInputStream getFIS() {
    return fis;
    } /**
     * 取得输出流
     */
    public FileOutputStream getFOS() {
    return fos;
    } /**
     * 删除文件, df是指字的文件名
     */
    public void deleteFile(String df) {
    File file = new File(df);
    file.delete();
    } /**
     * 拷贝文件内容fis->fos
     */
    public void movefile_FileStream() {
    try {
    File f = new File(infile);
    byte b[] = new byte[(int) (f.length())];
    fis.read(b);
    fos.write(b);
    } catch (IOException ioe) {
    System.out.println("调用DealFile.movefile_FileStream()函数错误:\r\n"
    + ioe);
    }
    } /**
     * 拷贝文件内容fis->fos
     */
    public void movefile_BufferedByteStream() {
    try {
    BufferedInputStream in = new BufferedInputStream(fis);
    BufferedOutputStream out = new BufferedOutputStream(fos);
    int c;
    while ((c = in.read()) != -1) {
    out.write(c);
    }
    in.close();
    out.close();
    } catch (IOException ioe) {
    System.out
    .println("调用DealFile.movefile_BufferedByteStream()函数错误:\r\n"
    + ioe);
    }
    } /**
     * 拷贝文件内容infile->outfile
     */
    public void movefile_BufferedCharStream() {
    try {
    BufferedReader in = new BufferedReader(new FileReader(infile));
    BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
    int c;
    while ((c = in.read()) != -1) {
    out.write(c);
    }
    in.close();
    out.close();
    } catch (IOException ioe) {
    System.out
    .println("调用DealFile.movefile_BufferedCharStream()函数错误:\r\n"
    + ioe);
    }
    } /**
     * 读中文字符串infile->
     */
    public String readCHStr() {
    return readCHStr(fis);
    } /**
     * 读中文字符串infile->
     */
    public String readCHStr(InputStream is) {
    String str = "";
    try {
    // 建立Unicode字符流
    InputStreamReader isw = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isw);
    // 读Unicode字符串
    String s = "";
    while ((s = br.readLine()) != null) {
    if (!str.equals("")) {
    str = str + "\r\n" + s;
    } else {
    str = str + s;
    }
    }
    br.close();
    isw.close();
    } catch (IOException ioe) {
    System.out.println("调用DealFile.readCHStr()函数错误:\r\n" + ioe);
    }
    return str;
    } /**
     * 将字符串转换为数据流
     */
    public FileInputStream toInputStream(String str) {
    FileInputStream fis_t = null;
    try {
    // 将字符串写入临时文件,再从文件生成数据流
    FileOutputStream fos_t = new FileOutputStream("tmp.txt");
    writeCHStr(fos_t, str);
    fis_t = new FileInputStream("tmp.txt");
    } catch (IOException ioe) {
    System.out.println("调用DealFile.toInputStream()函数错误:\r\n" + ioe);
    }
    return fis_t;
    } /**
     * 写中文字符串到文件->outfile
     */
    public void writeCHStr(String str) {
    writeCHStr(fos, str);
    } /**
     * 写中文字符串到文件->outfile
     */
    public void writeCHStr(OutputStream os, String str) {
    try {
    // 建立Unicode字符流
    OutputStreamWriter osw = new OutputStreamWriter(os);
    BufferedWriter bw = new BufferedWriter(osw);
    // 写Unicode字符串
    bw.write(str, 0, str.length());
    bw.newLine();
    bw.close();
    osw.close();
    } catch (IOException ioe) {
    System.out.println("调用DealFile.writeCHStr()函数错误:\r\n" + ioe);
    }
    } /**
     * 追加到文件结尾
     */
    public void appendCHStr(String outfile, String str) {
    try {
    RandomAccessFile rf = new RandomAccessFile(outfile, "rw");
    rf.seek(rf.length());
    rf.writeBytes(str);
    rf.close();
    } catch (IOException ioe) {
    System.out.println("调用DealFile.appendCHStr()函数错误:\r\n" + ioe);
    }
    } /**
     * 从位置cur开始检索第一个str的位置
     */
    public long seekStrPos(long cur, String str) {
    long fcur = cur;
    try {
    RandomAccessFile file = new RandomAccessFile(new File(infile), "r");
    long flen = file.length();
    int slen = str.length();
    byte b[] = new byte[slen]; for (; fcur < flen; fcur++) {
    file.seek(fcur);
    // 文件尾剩余长度不再够时
    if ((flen - fcur) < slen) {
    fcur = -1;
    break;
    }
    // 判断当前位置读取的字符串是否与参数字符串匹配,不是则继续搜索
    file.read(b, 0, slen);
    String bstr = new String(b);
    if (str.equals(bstr)) {
    break;
    }
    }
    file.close();
    } catch (IOException ioe) {
    System.out.println("调用DealFile.seekStrPos()函数错误:\r\n" + ioe);
    }
    return fcur;
    } /**
     * 在文件中定位某一个字符串在文件中的位置(左起)
     */
    public long seekStrPos(String str) {
    return seekStrPos(0, str);
    } /**
     * 在文件中定位从字符串str1开始, 第一个字符串str2的位置
     */
    public long seekStrPos(String str1, String str2) {
    long cur = seekStrPos(0, str1);
    return seekStrPos(cur, str2);
    } /**
     * 从文件的pos位置开始, 取长度为len的字符串
     */
    public String substring(long pos, int len) {
    String str = "";
    try {
    RandomAccessFile file = new RandomAccessFile(new File(infile), "r");
    long flen = file.length();
    // 当不能返回时返回空值
    if (pos < 0 || (flen - pos) < len) {
    return "";
    }
    file.seek(pos);
    byte b[] = new byte[len];
    file.read(b, 0, len);
    str = new String(b);
    file.close();
    } catch (IOException ioe) {
    System.out.println("调用DealFile.substring()函数错误:\r\n" + ioe);
    }
    return str;
    } /**
     * 从字符串str1开始 , 检索str2后, 长度为len的字符串
     */
    public String substring(String str1, String str2, int len) {
    long pos = seekStrPos(str1, str2);
    return substring(pos + str2.length(), len).trim();
    } public static void main(String args[]) throws IOException,
    ArrayIndexOutOfBoundsException {
    DealFile df = new DealFile();

    // *追加文件方法(一旦作为输出文件被打开,即被清空)
    df.connFIS("out.txt");
    String str = df.readCHStr() + "测试追加WWWWWWWWTTTTW我的还"; df.connFOS("out.txt");
    df.writeCHStr(str);
    df.closeFIS();
    df.closeFOS();
    // 拷贝文件
    df.connFIS("out.txt");
    df.connFOS("in.txt");
    df.movefile_FileStream();
    df.movefile_BufferedByteStream();
    df.movefile_BufferedCharStream();
    df.closeFIS();
    df.closeFOS();
    df.connFIS("out.txt");
    System.out.println(df.substring("flyline", "background-color:", 7)
    .toUpperCase());
    df.closeFIS();
    }
    }
      

  16.   

    最简单的是调用 系统的copy函数
      

  17.   

     static int checkagain(String srcDir,String decDir){
                .
                .
                .
     checkagain(srcDir+File.separator+file[i].getName(),decDir+File.separator+file[i].getName());}
    我经常写方法, 基本没写过这种 自己调用自己的方法, 最近看了好几个这种方法,主要是想问  你们写这种方法的思路是怎么样,意思就是说你们怎么想到这样写的?很想学习.