利用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);
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM