`

java 文件操作大全

阅读更多

import  java.io.*;  
 
public  class  FileOperate  {  
   public  FileOperate()  {  
   }  
 
   /**  
     *  新建目录  
     *  @param  folderPath  String  如  c:/fqf  
     *  @return  boolean  
     */  
   public  void  newFolder(String  folderPath)  {  
       try  {  
           String  filePath  =  folderPath;  
           filePath  =  filePath.toString();  
           java.io.File  myFilePath  =  new  java.io.File(filePath);  
           if  (!myFilePath.exists())  {  
               myFilePath.mkdir();  
           }  
       }  
       catch  (Exception  e)  {  
           System.out.println("新建目录操作出错");  
           e.printStackTrace();  
       }  
   }  
 
   /**  
     *  新建文件  
     *  @param  filePathAndName  String  文件路径及名称  如c:/fqf.txt  
     *  @param  fileContent  String  文件内容  
     *  @return  boolean  
     */  
   public  void  newFile(String  filePathAndName,  String  fileContent)  {  
 
       try  {  
           String  filePath  =  filePathAndName;  
           filePath  =  filePath.toString();  
           File  myFilePath  =  new  File(filePath);  
           if  (!myFilePath.exists())  {  
               myFilePath.createNewFile();  
           }  
           FileWriter  resultFile  =  new  FileWriter(myFilePath);  
           PrintWriter  myFile  =  new  PrintWriter(resultFile);  
           String  strContent  =  fileContent;  
           myFile.println(strContent);  
           resultFile.close();  
 
       }  
       catch  (Exception  e)  {  
           System.out.println("新建目录操作出错");  
           e.printStackTrace();  
 
       }  
 
   }  
 
   /**  
     *  删除文件  
     *  @param  filePathAndName  String  文件路径及名称  如c:/fqf.txt  
     *  @param  fileContent  String  
     *  @return  boolean  
     */  
   public  void  delFile(String  filePathAndName)  {  
       try  {  
           String  filePath  =  filePathAndName;  
           filePath  =  filePath.toString();  
           java.io.File  myDelFile  =  new  java.io.File(filePath);  
           myDelFile.delete();  
 
       }  
       catch  (Exception  e)  {  
           System.out.println("删除文件操作出错");  
           e.printStackTrace();  
 
       }  
 
   }  

---------------------------------------
 
   /**  
     *  删除文件夹  
     *  @param  filePathAndName  String  文件夹路径及名称  如c:/fqf  
     *  @param  fileContent  String  
     *  @return  boolean  
     */  
   public  void  delFolder(String  folderPath)  {  
       try  {  
           delAllFile(folderPath);  //删除完里面所有内容  
           String  filePath  =  folderPath;  
           filePath  =  filePath.toString();  
           java.io.File  myFilePath  =  new  java.io.File(filePath);  
           myFilePath.delete();  //删除空文件夹  
 
       }  
       catch  (Exception  e)  {  
           System.out.println("删除文件夹操作出错");  
           e.printStackTrace();  
 
       }  
 
   }  
 
   /**  
     *  删除文件夹里面的所有文件  
     *  @param  path  String  文件夹路径  如  c:/fqf  
     */  
   public  void  delAllFile(String  path)  {  
       File  file  =  new  File(path);  
       if  (!file.exists())  {  
           return;  
       }  
       if  (!file.isDirectory())  {  
           return;  
       }  
       String[]  tempList  =  file.list();  
       File  temp  =  null;  
       for  (int  i  =  0;  i  <  tempList.length;  i++)  {  
           if  (path.endsWith(File.separator))  {  
               temp  =  new  File(path  +  tempList[i]);  
           }  
           else  {  
               temp  =  new  File(path  +  File.separator  +  tempList[i]);  
           }  
           if  (temp.isFile())  {  
               temp.delete();  
           }  
           if  (temp.isDirectory())  {  
               delAllFile(path+"/"+  tempList[i]);//先删除文件夹里面的文件  
               delFolder(path+"/"+  tempList[i]);//再删除空文件夹  
           }  
       }  
   }  
 
   /**  
     *  复制单个文件  
     *  @param  oldPath  String  原文件路径  如:c:/fqf.txt  
     *  @param  newPath  String  复制后路径  如:f:/fqf.txt  
     *  @return  boolean  
     */  
   public  void  copyFile(String  oldPath,  String  newPath)  {  
       try  {  
           int  bytesum  =  0;  
           int  byteread  =  0;  
           File  oldfile  =  new  File(oldPath);  
           if  (oldfile.exists())  {  //文件存在时  
               InputStream  inStream  =  new  FileInputStream(oldPath);  //读入原文件  
               FileOutputStream  fs  =  new  FileOutputStream(newPath);  
               byte[]  buffer  =  new  byte[1444];  
               int  length;  
               while  (  (byteread  =  inStream.read(buffer))  !=  -1)  {  
                   bytesum  +=  byteread;  //字节数  文件大小  
                   System.out.println(bytesum);  
                   fs.write(buffer,  0,  byteread);  
               }  
               inStream.close();  
           }  
       }  
       catch  (Exception  e)  {  
           System.out.println("复制单个文件操作出错");  
           e.printStackTrace();  
 
       }  
 
   }  
 
   /**  
     *  复制整个文件夹内容  
     *  @param  oldPath  String  原文件路径  如:c:/fqf  
     *  @param  newPath  String  复制后路径  如:f:/fqf/ff  
     *  @return  boolean  
     */  
   public  void  copyFolder(String  oldPath,  String  newPath)  {  
 
       try  {  
           (new  File(newPath)).mkdirs();  //如果文件夹不存在  则建立新文件夹  
           File  a=new  File(oldPath);  
           String[]  file=a.list();  
           File  temp=null;  
           for  (int  i  =  0;  i  <  file.length;  i++)  {  
               if(oldPath.endsWith(File.separator)){  
                   temp=new  File(oldPath+file[i]);  
               }  
               else{  
                   temp=new  File(oldPath+File.separator+file[i]);  
               }  
 
               if(temp.isFile()){  
                   FileInputStream  input  =  new  FileInputStream(temp);  
                   FileOutputStream  output  =  new  FileOutputStream(newPath  +  "/"  +  
                           (temp.getName()).toString());  
                   byte[]  b  =  new  byte[1024  *  5];  
                   int  len;  
                   while  (  (len  =  input.read(b))  !=  -1)  {  
                       output.write(b,  0,  len);  
                   }  
                   output.flush();  
                   output.close();  
                   input.close();  
               }  
               if(temp.isDirectory()){//如果是子文件夹  
                   copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);  
               }  
           }  
       }  
       catch  (Exception  e)  {  
           System.out.println("复制整个文件夹内容操作出错");  
           e.printStackTrace();  
 
       }  
 
   }  
 
   /**  
     *  移动文件到指定目录  
     *  @param  oldPath  String  如:c:/fqf.txt  
     *  @param  newPath  String  如:d:/fqf.txt  
     */  
   public  void  moveFile(String  oldPath,  String  newPath)  {  
       copyFile(oldPath,  newPath);  
       delFile(oldPath);  
 
   }  
 
   /**  
     *  移动文件到指定目录  
     *  @param  oldPath  String  如:c:/fqf.txt  
     *  @param  newPath  String  如:d:/fqf.txt  
     */  
   public  void  moveFolder(String  oldPath,  String  newPath)  {  
       copyFolder(oldPath,  newPath);  
       delFolder(oldPath);  
 
   }  
}

 

 

------------------

Java实现文件拷贝的4种方法
第一种方法:古老的方式

 

 public static long forJava(File f1,File f2) throws Exception{
  long time=new Date().getTime();
  int length=2097152;
  FileInputStream in=new FileInputStream(f1);
  FileOutputStream out=new FileOutputStream(f2);
  byte[] buffer=new byte[length];
  while(true){
   int ins=in.read(buffer);
   if(ins==-1){
    in.close();
    out.flush();
    out.close();
    return new Date().getTime()-time;
   }else
    out.write(buffer,0,ins);
  }
 }
方法的2参数分别是原始文件,和拷贝的目的文件.这里不做过多介绍.

实现方法很简单,分别对2个文件构建输入输出流,并且使用一个字节数组作为我们内存的缓存器, 然后使用流从f1 中读出数据到缓存里,在将缓存数据写到f2里面去.这里的缓存是2MB的字节数组

第2种方法:使用NIO中的管道到管道传输

 

    public static long forTransfer(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        int i=0;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();

             retrun

 #0000ff">new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<20971520)
                length=(int)(inC.size()-inC.position());
            else
                length=20971520;
            inC.transferTo(inC.position(),length,outC);
            inC.position(inC.position()+length);
            i++;
        }
    }

实现方法:在第一种实现方法基础上对输入输出流获得其管道,然后分批次的从f1的管道中像f2的管道中输入数据每次输入的数据最大为2MB


方法3:内存文件景象写(读文件没有使用文件景象,有兴趣的可以回去试试,,我就不试了,估计会更快)

 

    public static long forImage(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        RandomAccessFile out=new RandomAccessFile(f2,"rw");
        FileChannel inC=in.getChannel();
        MappedByteBuffer outC=null;
        MappedByteBuffer inbuffer=null;
        byte[] b=new byte[length];
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.force();
                out.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())
yle="COLOR: #000000"><length){
                length=(int)(inC.size()-inC.position());
            }else{
                length=20971520;
            }
            b=new byte[length];
            inbuffer=inC.map(MapMode.READ_ONLY,inC.position(),length);
            inbuffer.load();
            inbuffer.get(b);
            outC=out.getChannel().map(MapMode.READ_WRITE,inC.position(),length);
            inC.position(b.length+inC.position());
            outC.put(b);
            outC.force();
        }
    }

实现方法:跟伤2个例子不一样,这里写文件流没有使用管道而是使用内存文件映射(假设文件f2在内存中).在循环中从f1的管道中读取数据到字节数组里,然后在像内存映射的f2文件中写数据.


第4种方法:管道对管道

 

    public static long forChannel(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        ByteBuffer b=null;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<length){
                length=(int OR: #000000">)(inC.size()-inC.position());
            }else
                length=2097152;
            b=ByteBuffer.allocateDirect(length);
            inC.read(b);
            b.flip();
            outC.write(b);
            outC.force(false);
        }
    }

这里实现方式与第3种实现方式很类似,不过没有使用内存影射.

 

下面是对49.3MB的文件进行拷贝的测试时间(毫秒)

Start Copy File...  file size:50290KB
CopyFile:b1.rmvb mode:forChannel  RunTime:3203
CopyFile:b1.rmvb mode:forImage  RunTime:3328
CopyFile:b1.rmvb mode:forJava  RunTime:2172
CopyFile:b1.rmvb mode:forTransfer RunTime:1406
End Copy File!

解释: 在测试结果中看到 古老方式,和管道向管道传输是最快的,,,,,为什么呢?

我分析是这样的,由于另外2种方法内部都使用了 字节数组作为缓存中转,在加上NIO内部有一个贴近系统的缓存区,这无意就增加了另一个缓存器,所以相对于这2个方法就要慢许多,,如果不使用 字节数组作为数据中转的话相信速度会更快的..


评论

相关推荐

    Java 文件操作大全

    在Java编程中,文件操作是至关重要的,它允许程序与文件系统进行交互,执行诸如读取、写入、追加、删除、移动和复制等操作。本篇文章将深入探讨Java中的文件操作,特别是基于IO流的读取方法。 首先,我们来看如何...

    java文件操作大全

    java文件操作大全

    Java文件操作大全

    最全的java文件操作大全,包括文件的存储,建立,判断文件是否存在,建立文件删除文件,附加源码!!!

    Java文件操作大全.rar_文件操作

    `Java文件操作大全 (3).txt、Java文件操作大全 (1).txt、Java文件操作大全 (2).txt`这些文档很可能是教程的章节,逐步讲解各个知识点。而`www.pudn.com.txt`可能是一个示例文件或参考资料链接。 总的来说,这...

    java文件操作大全.chm

    java文件操作大全.chm

    《Java文件操作大全》电子书

    《Java文件操作大全》电子书 本文汇集常用文件操作方法,包括文件的建立/检查与删除,目录的建立/检查与删除,取出目录中文件,文件属性的取得,逐行读取数据等等。

    Java文件操作大全[汇编].pdf

    Java文件操作大全[汇编].pdf

    java 文件操作大全107种情况

    java 文件操作 包括 文件删除 导出jsp Word 格式文件 ,文件合并修改等。

    java文件操作类

    java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java文件操作类java...

    java文件读写操作大全java文件读写操作大全

    Java 文件读写操作大全 Java 文件读写操作大全是 Java 语言中对文件进行读写操作的详细介绍。下面将对 Java 文件读写操作大全中的知识点进行详细解释。 一、获得控制台用户输入的信息 Java 中可以使用 `System.in...

    java视频教程—Java文件操作

    java视频教程 Java文件操作 JavaFile

    Java文件操作封装类

    Java文件操作封装类

    java文件操作工具类

    java文件操作工具类是java中针对文件操作的一个工具类,可以方便的读取,下载,上传文件等操作,希望可以帮到大家。

    JAVA代码实现远程操作服务器文件

    Session是一个远程服务器文件操作的会话,可以实现文件的移动、复制、删除等操作。通过使用Session,可以实现远程服务器文件的操作。 6. 使用InputStream和BufferedReader实现命令执行结果的获取 InputStream和...

    java实现对文件的各种操作的工具类.md

    # java实现对文件的各种操作的工具类 ## 可以实现的操作有: 1. 删除单个文件 2. 删除文件夹及文件夹下的文件 3. 使用文件流对单个文件进行复制 4. 复制整个文件夹内容(包含子文件夹中的所有内容) 5. ...

    java 移动文件.

    "Java 文件操作" Java 文件操作是 Java 编程语言中的一种基本操作,包括文件的移动、复制、删除、剪切等。下面是关于 Java 文件操作的知识点总结: 一、文件移动 文件移动是指将文件从一个目录下移到另一个目录下...

    java实现windows文件系统操作监控

    Java的`java.nio.file`包提供了丰富的文件操作接口,如`Files.setPosixFilePermissions()`和`Files.newFileChannel()`,可以用来设置权限和创建文件通道进行锁定。 7. **文件自动加密**:文件加密通常涉及对文件...

    java文件读写操作

    这个文件里面包含了java的IO流对文件的操作和java通道加内存映射对文件操作的源码

    Java文件操作一例:Copy 复制文件.rar

    Java文件操作一例:Copy 复制文件,虽然是复制文件,不过通过本源码你可以学习很多相关的Java基础技巧,比如Java对文件的事件处理、取得目录内容的事件处理、如何弹出文件选择器、如何得到选择文件的绝对路径、如何...

Global site tag (gtag.js) - Google Analytics