利用Java对本地磁盘的文件重命名

一、需求

  

不管是C/C++还是JAVA,都可能生成一些持久性数据,我们可以将数据存储在文件或数据库中,
此项目主要训练学习Java对本地磁盘的文件重命名,例如C:\nowcoder.txt重命名C:\nowcoder2.txt

  

二、代码实现

 1 package com.wordcount.demo;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.File;
 6 import java.io.FileReader;
 7 import java.io.FileWriter;
 8 
 9 public class FileRename {
10     //Main
11     public static void main(String[] args) {
12         String filePath = "E:\\demo\\file";
13         if (isFile(filePath)) {
14             System.out.println("这是一个文件!");
15             rename(filePath, newPath(filePath));
16         } else {
17             System.out.println("这是一个文件夹!");
18             reName(filePath);
19         }
20     }
21     //利用缓冲流进行文件读写
22     public static void rename(String filePath, String newPath) {
23         BufferedReader bufR = null;
24         BufferedWriter bufW = null;
25         try {
26             bufR = new BufferedReader(new FileReader(new File(filePath)));
27             bufW = new BufferedWriter(new FileWriter(new File(newPath)));
28             String line;
29             while ((line = bufR.readLine()) != null) {
30                 bufW.write(line);
31             }
32         } catch (Exception e) {
33             e.printStackTrace();
34         } finally {
35             try {
36                 bufW.close();
37                 bufR.close();
38             } catch (Exception e) {
39                 e.printStackTrace();
40             }
41         }
42     }
43     //判断是不是一个文件
44     public static boolean isFile(String filePath) {
45         File file = new File(filePath);
46         if (file.isDirectory()) {
47             return false;
48         } else if (file.isFile()) {
49             return true;
50         } else {
51             return false;
52         }
53     }
54     //切割生成新路径
55     public static String newPath(String filePath) {
56         int temp = filePath.lastIndexOf('.');
57         int length = filePath.length();
58         String newPath = filePath.substring(0, temp) + "2" + filePath.substring(temp, length);
59         return newPath;
60     }
61     //不切割利用renameTo进行重命名
62     public static void reName(String filePath) {
63         String newPath = filePath + "2";
64         boolean flag = new File(filePath).renameTo(new File(newPath));
65         System.out.println(flag);
66     }
67 }

三、一些收获

  1、文件复制时间对比(三种方法)

  

  1 package com.file;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.io.InputStream;
  9 import java.io.OutputStream;
 10 import java.nio.ByteBuffer;
 11 import java.nio.MappedByteBuffer;
 12 import java.nio.channels.FileChannel;
 13 import java.text.DateFormat;
 14 import java.text.SimpleDateFormat;
 15 import java.util.Date;
 16 
 17 public class OperateFileDemo {
 18 
 19     private DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");
 20     private Date start_time = null;//开始时间
 21     private Date end_time = null;//结束时间
 22 
 23     public static void main(String[] args) {
 24         OperateFileDemo demo = new OperateFileDemo();
 25         demo.operateFile1();
 26         demo.operateFile2();
 27         demo.operateFile3();
 28         demo.fileCopy1();
 29         demo.fileCopy2();
 30     }
 31 
 32     /**
 33      * the first method of reading file
 34      */
 35     public void operateFile1(){
 36         start_time = new Date();
 37         File f = new File("E:"+File.separator+"test.txt");//File.separator——windows is '\',unix is '/'
 38         try {
 39             //创建一个流对象
 40             InputStream in = new FileInputStream(f);
 41             //读取数据,并将读取的数据存储到数组中
 42             byte[] b = new byte[(int) f.length()];//数据存储的数组
 43             int len = 0;
 44             int temp = 0;
 45             while((temp = in.read()) != -1){//循环读取数据,未到达流的末尾
 46                 b[len] = (byte) temp;//将有效数据存储在数组中
 47                 len ++;
 48             }
 49 
 50             System.out.println(new String(b, 0, len, "GBK"));
 51             in.close();
 52         } catch (FileNotFoundException e) {
 53             e.printStackTrace();
 54         } catch (IOException e) {
 55             e.printStackTrace();
 56         }finally{
 57             end_time = new Date();
 58             System.out.println("=第一种方式——start_time:"+df.format(start_time));
 59             System.out.println("=第一种方式——end_time:"+df.format(end_time));
 60             System.out.println("=第一种方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
 61         }
 62     }
 63 
 64     /**
 65      * the second method of reading file
 66      */
 67     public void operateFile2(){
 68         start_time = new Date();
 69         File f = new File("E:"+File.separator+"test.txt");
 70         try {
 71             InputStream in = new FileInputStream(f);
 72             byte[] b = new byte[1024];
 73             int len = 0;
 74             while((len = in.read(b)) != -1){
 75                 System.out.println(new String(b, 0, len, "GBK"));
 76             }
 77             in.close();
 78         } catch (FileNotFoundException e) {
 79             e.printStackTrace();
 80         } catch (IOException e) {
 81             e.printStackTrace();
 82         }finally{
 83             end_time = new Date();
 84             System.out.println("=第二种方式——start_time:"+df.format(start_time));
 85             System.out.println("=第二种方式——end_time:"+df.format(end_time));
 86             System.out.println("=第二种方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
 87         }
 88     }
 89 
 90     /**
 91      * the third method of reading file(文件读取(Memory mapping-内存映射方式))
 92      * 这种方式的效率是最好的,速度也是最快的,因为程序直接操作的是内存
 93      */
 94     public void operateFile3(){
 95         start_time = new Date();
 96         File f = new File("E:"+File.separator+"test.txt");
 97         try {
 98             FileInputStream in = new FileInputStream(f);
 99             FileChannel chan = in.getChannel();//内存与磁盘文件的通道,获取通道,通过文件通道读写文件。
100             MappedByteBuffer buf = chan.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
101             byte[] b = new byte[(int) f.length()];
102             int len = 0;
103             while(buf.hasRemaining()){
104                 b[len] = buf.get();
105                 len++;
106             }
107             chan.close();
108             in.close();
109             System.out.println(new String(b,0,len,"GBK"));
110         } catch (FileNotFoundException e) {
111             e.printStackTrace();
112         } catch (IOException e) {
113             e.printStackTrace();
114         }finally{
115             end_time = new Date();
116             System.out.println("=第三种方式——start_time:"+df.format(start_time));
117             System.out.println("=第三种方式——end_time:"+df.format(end_time));
118             System.out.println("=第三种方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
119         }
120     }
121 
122     /**
123      * the first method of copying file
124      */
125     public void fileCopy1(){
126         start_time = new Date();
127         File f = new File("E:"+File.separator+"test.txt");
128         try {
129             InputStream in = new FileInputStream(f);
130             OutputStream out = new FileOutputStream("F:"+File.separator+"test.txt");
131             int len = 0;
132             while((len = in.read()) != -1){
133                 out.write(len);
134             }
135             out.close();
136             in.close();
137         } catch (FileNotFoundException e) {
138             e.printStackTrace();
139         } catch (IOException e) {
140             e.printStackTrace();
141         }finally{
142             end_time = new Date();
143             System.out.println("=第一种文件复制方式——start_time:"+df.format(start_time));
144             System.out.println("=第一种文件复制方式——end_time:"+df.format(end_time));
145             System.out.println("=第一种文件复制方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
146         }
147     }
148 
149     /**
150      * 使用内存映射实现文件复制操作
151      */
152     public void fileCopy2(){
153         start_time = new Date();
154         File f = new File("E:"+File.separator+"test.txt");
155         try {
156             FileInputStream in = new FileInputStream(f);
157             FileOutputStream out = new FileOutputStream("F:"+File.separator+"test2.txt");
158             FileChannel inChan = in.getChannel();
159             FileChannel outChan = out.getChannel();
160             //开辟缓冲区
161             ByteBuffer buf = ByteBuffer.allocate(1024);
162             while ((inChan.read(buf)) != -1){
163                 //重设缓冲区
164                 buf.flip();
165                 //输出缓冲区
166                 outChan.write(buf);
167                 //清空缓冲区
168                 buf.clear();
169             }
170             inChan.close();
171             outChan.close();
172             in.close();
173             out.close();
174         } catch (FileNotFoundException e) {
175             e.printStackTrace();
176         } catch (IOException e) {
177             e.printStackTrace();
178         }finally{
179             end_time = new Date();
180             System.out.println("=第二种文件复制方式——start_time:"+df.format(start_time));
181             System.out.println("=第二种文件复制方式——end_time:"+df.format(end_time));
182             System.out.println("=第二种文件复制方式总耗时:"+(end_time.getTime() - start_time.getTime())+"毫秒");
183         }
184     }
185 }
View Code

  2、renameTo方法

  官方文档

/**
 * 
 重新命名此抽象路径名表示的文件。
 此方法行为的许多方面都是与平台有关的:重命名操作无法将一个文件从
 一个文件系统移动到另一个文件系统,
 该操作不是不可分的,如果已经存在具有目标抽象路径名的文件,
 那么该操作可能无法获得成功。应该始终检查返回值,以确保重命名操作成功。

 参数:
 dest - 指定文件的新抽象路径名
 返回:
 当且仅当重命名成功时,返回 true;否则返回 false
 抛出:
 SecurityException - 如果存在安全管理器,且其 SecurityManager.checkWrite(java.lang.String) 方法拒绝对原路径名和新路径名进行写访问
 NullPointerException - 如果参数 dest 为 null
 */
public boolean renameTo(File dest) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
            security.checkWrite(dest.path);
        }
        if (dest == null) {
            throw new NullPointerException();
        }
        if (this.isInvalid() || dest.isInvalid()) {
            return false;
        }
        return fs.rename(this, dest);
    }

  

猜你喜欢

转载自www.cnblogs.com/null-/p/10014790.html