1. 程式人生 > >利用Java對本地磁碟的檔案重新命名

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