Java File類(文件的讀取,寫入,復制與重命名)


文件的重命名   file.reNameTo()

public boolean renameTo(File dest)
重新命名此抽象路徑名表示的文件。

此方法行為的許多方面都是與平台有關的:重命名操作無法將一個文件從一個文件系統移動到另一個文件系統,dest為新命名的抽象文件

  

public boolean ReName(String path,String newname) {//文件重命名
        //Scanner scanner=new Scanner(System.in);
        File file=new File(path);
        if(file.exists()) {
        File newfile=new File(file.getParent()+File.separator+newname);//創建新名字的抽象文件
        if(file.renameTo(newfile)) {
            System.out.println("重命名成功!"); 
            return true;
        }
        else {
            System.out.println("重命名失敗!新文件名已存在");
            return false;
        }
        }
        else {
            System.out.println("重命名文件不存在!");
            return false;
        }
    
    }

 

 

文件內容的讀取

        File f2=new File(f1,"test.txt");//第一個參數為一個目錄文件,第二個參數為要在當前f1目錄下要創建的文件
        
        InputStreamReader reader=new InputStreamReader(new FileInputStream(f2),"GBK");
        BufferedReader bfreader=new BufferedReader(reader);
        String line;
        while((line=bfreader.readLine())!=null) {//包含該行內容的字符串,不包含任何行終止符,如果已到達流末尾,則返回 null
            System.out.println(line);
        }
        

以上方法用於讀取文本類文件

  FileInputStream 從文件系統中的某個文件中獲得輸入字節。哪些文件可用取決於主機環境。

InputStreamReader 是字節流通向字符流的橋梁 第二個參數可以設置字符集

BufferedReader 內包裝 InputStreamReader   從字符輸入流中讀取文本,緩沖各個字符,從而實現字符、數組和行的高效讀取。

建議用 BufferedReader 包裝所有其 read() 操作可能開銷很高的 Reader(如 FileReader 和 InputStreamReader)

 

 

文件的寫入

File f1=new File("H://asc//");//傳入文件/目錄的路徑
        File f2=new File(f1,"test.txt");//第一個參數為一個目錄文件,第二個參數為要在當前f1目錄下要創建的文件
        
        PrintWriter printWriter =new PrintWriter(new FileWriter(f2,true),true);//第二個參數為true,從文件末尾寫入 為false則從開頭寫入
        printWriter.println("I am your father");
        printWriter.close();//記得關閉輸入流
        

使用 FileWriter寫入字符流    如果要寫入諸如圖像數據之類的原始字節的流使用FileOutputStream 。

FileWriter

public FileWriter(String fileName,
                  boolean append)
參數:fileName - 一個字符串,表示與系統有關的文件名。append - 一個 boolean 值,如果為 true,則將數據寫入文件末尾處,而不是寫入文件開始處。

PrintWriter

public PrintWriter(OutputStream out,
                   boolean autoFlush)
autoFlush - boolean 變量;如果為 true,則 println、 printf 或 format 方法將自動刷新輸出緩沖區 如果沒有這個參數或者為 false 需要刷新緩沖輸入區 fllush()




文件/文件夾的復制

文件的復制采用的思路是 先在目標路徑下創建好空文件 在利用輸入輸出流 將從源文件中讀取到的數據寫入到新文件中

public void copyFile(String oldfilepath,String newpath) {//復制文件
        File oldfile=new File(oldfilepath);
        File newfile=new File(newpath+File.separator+oldfile.getName());//創建新抽象文件
        if(!oldfile.exists()||!oldfile.isFile()) {
            System.out.println("復制文件莫得¿¿¿");
            return;
        }
        if(newfile.exists()) {//新文件路徑下有同名文件
            System.out.println("是否覆蓋原有文件¿(y不覆蓋|n覆蓋)");
            Scanner scanner=new Scanner(System.in);
            String string=scanner.nextLine();
            if(string=="n") {
                newfile.delete();
                try {
                    newfile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else {
                newfile=new    File(newpath+File.separator+"(1)"+newfile.getName());
                try {
                    newfile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        else {
                try {
                    newfile.createNewFile();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        
        try {
            FileInputStream fin=new FileInputStream(oldfile);//輸入流
            try {
                FileOutputStream fout=new FileOutputStream(newfile,true);//輸出流
                byte[]b=new byte[1024];
                try {
                    while((fin.read(b))!=-1) {//讀取到末尾 返回-1 否則返回讀取的字節個數
                        fout.write(b);
                    }
                    fin.close();
                    fout.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

文件夾的復制

如果是空文件夾倒還好說,直接新建同名文件夾 。但如果是含有文件內容的文件夾的話  需要使用深度優先遍歷文件夾。 如果是文件夾 就在對應路徑下創建空文件夾 再遞歸調用函數遍歷自身   如果是文件 則直接復制過來

    
    public void dfs(File f1,File f2) {//f1要復制的文件    f2要復制到的路徑
        
        if(f1.isFile()&&f1.exists()) {//文件
            copyFile(f1.getAbsolutePath(), f2.getAbsolutePath());
            return;
        }
        if(f1.isDirectory()) {
            File file2=new File(f2.getAbsoluteFile()+File.separator+f1.getName());
            
            file2.mkdirs();
            String []list=f1.list();
            for (int i = 0; i < list.length; i++) {
                File file1=new File(f1.getAbsoluteFile()+File.separator+list[i]);
                dfs(file1, file2);
            }
        }
    }
    
    public void copydir(String oldfilepath,String newfilepath) {//復制文件夾
        File oldfile=new File(oldfilepath);
        File newfile=new File(newfilepath+File.separator+oldfile.getName());
        if(!oldfile.exists()||!oldfile.isDirectory()) {
            System.out.println("此文件夾不存在!");
            return;
        }
        
        if(newfile.exists()) {
            System.out.println("是否覆蓋原有文件夾¿(y不覆蓋|n覆蓋)");
            Scanner scanner=new Scanner(System.in);
            String string=scanner.nextLine();
            if(string=="n") {
                deleteFile(newfile.getAbsolutePath());
                
            }
            else
                return;
        }
        //dfs
        dfs(oldfile, new File(newfilepath));
            
        return;
            
    }

注意 再使用輸入輸出流后記得 用close()函數關閉 輸入輸出流.  如果一個文件被打開着 沒被關閉  另一個程序想要訪問時 就會報錯異常

文件輸出流是用於將數據寫入 File 或 FileDescriptor 的輸出流。文件是否可用或能否可以被創建取決於基礎平台。
特別是某些平台一次只允許一個 FileOutputStream(或其他文件寫入對象)打開文件進行寫入。在這種情況下,如果所涉及的文件
已經打開,則此類中的構造方法將失敗


免責聲明!

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



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