JAVA學習(八):JAVA檔案編程

來源:互聯網
上載者:User

標籤:檔案編程   檔案遍曆   檔案讀寫   

本博文主要介紹JAVA檔案編程,主要包括通過JDK提供的I/O來從檔案讀取和寫入資料、位元組流讀寫檔案的方法、字元流讀寫檔案的方法、如何使用File類建立、刪除和遍曆檔案與目錄等操作。


不管是C/C++還是JAVA,都可能產生一些持久性資料,我們可以將資料存放區在檔案或資料庫中,但是對於一些簡單性的資料,如果儲存在資料庫中,則會顯得有點得不償失了,那麼,如何在JAVA中將資料存放區在檔案中就成了中小型程式必須掌握的基本技能了。


下面一一講解File類簡介與檔案的建立、刪除、重新命名,檔案夾的建立、重新命名、刪除,檔案屬性的讀取,檔案屬性的設定,遍曆檔案夾,檔案的簡單讀寫,並且都給出範例程式碼。


1、File類簡介與檔案的建立、刪除、重新命名


主要內容包括File類,File類用來代表檔案或檔案夾,通過File類,可以對檔案與檔案夾執行豐富的操作,並且可以擷取檔案的路徑、大小、檔案名稱等資訊;通過檔案類的creatNewFile()方法建立檔案,通過delete()方法刪除檔案,使用renameTo()方法重新命名檔案。

import java.io.File;import java.io.IOException;public class HelloFile {public static void main(String[] args) {// TODO Auto-generated method stubFile file = new File("hello.txt");//預設存在相對路徑下,即該工程下//File file = new File("bin/hello.txt");//檔案存在於指定的絕對路徑下//File file = new File("../hello.txt");//檔案存在於該工程路徑的上一級//File file = new File("../../hello.txt");//檔案存在於該工程路徑的上一級的上一級//判斷檔案是否存在if(file.exists()){//列印“檔案”屬性System.out.println(file.isFile());//列印“路徑(檔案夾)”屬性System.out.println(file.isDirectory());////同目錄重新命名//File nameto = new File("NewHello.txt");//file.renameTo(nameto);////跨目錄重新命名////注意1:檔案夾結構必須處於同一個分區////注意2:檔案若處於不同的分區,需要使用檔案的拷貝,而不是重新命名//File nameto = new File("src/NewHello.txt");//file.renameTo(nameto);////刪除檔案//file.delete();//System.out.println("檔案刪除成功!");}else{System.out.println("檔案不存在!");try {file.createNewFile();System.out.println("檔案已經成功建立!");} catch (IOException e) {System.out.println("檔案無法建立!");}}}}



2、檔案夾的建立、重新命名、刪除


主要內容包括通過使用mkdir()與mkdirs()方法建立檔案夾,使用delete()方法刪除檔案夾,使用renameTo()方法重新命名檔案夾

import java.io.File;public class HelloFolder {public static void main(String[] args) {//建立單級檔案夾:folder.mkdir()File folder1 = new File("MyFolder1");//if(folder1.mkdir())//{//System.out.println("單級檔案夾建立完成!");//}//else//{//if(folder1.exists())//{//System.out.println("單級檔案夾已經存在,不用建立!");//}//else//{//System.out.println("單級檔案夾建立失敗!");//}//}//建立多級檔案夾:folder.mkdirs()File folder2 = new File("MyFolder2/one/two");//if(folder2.mkdirs())//{//System.out.println("多級檔案夾建立完成!");//}//else//{//if(folder2.exists())//{//System.out.println("多級檔案夾已經存在,不用建立!");//}//else//{//System.out.println("多級檔案夾建立失敗!");//}//}////檔案夾重新命名////重新命名同一級檔案夾//File newfolder1 =new File("MyFolder3");//if(folder1.renameTo(newfolder1))//{//System.out.println("Done!");//}else{//System.out.println("Fail!");//}////重新命名不同級的檔案夾,有點類似於移動,但仍歸類於重新命名////注意:處於同一分區中//File newfolder2 =new File("MyFolder2/two");//if(folder2.renameTo(newfolder2))//{//System.out.println("Done!");//}else{//System.out.println("Fail!");//}//刪除檔案夾if(folder1.delete()){System.out.println("刪除完成!");}else{System.out.println("刪除失敗!");}////注意:只能刪除空檔案夾//folder2.delete();}}



3、檔案屬性的讀取


主要內容包括判斷檔案是否存在、檔案名稱、路徑、檔案大小、是否被隱藏、是否可讀可寫、是否為檔案夾等。

import java.io.File;public class ReadFileProperty {public static void main(String[] args) {File file = new File("text.txt");//判斷檔案是否存在System.out.println("檔案是否存在"+file.exists());//讀檔案名稱System.out.println("讀取檔案名稱"+file.getName());//讀取檔案路徑(相對路徑)System.out.println("讀取檔案相對路徑"+file.getPath());//讀取絕對路徑System.out.println("讀取檔案絕對路徑"+file.getAbsolutePath());//讀取檔案父級路徑System.out.println("讀取檔案父級路徑"+file.getParent());//返回相對路徑的上一級System.out.println("讀取檔案父級路徑"+ new File(file.getAbsolutePath()).getParent());//返回絕對路徑的上一級//讀取檔案大小System.out.println("讀取檔案大小"+file.length()+"byte");System.out.println("讀取檔案大小"+(float)file.length()/1000+"KB");//判斷檔案是否被隱藏System.out.println("判斷檔案是否被隱藏"+file.isHidden());//判斷檔案是否可讀System.out.println("判斷檔案是否可讀"+file.canRead());//判斷檔案是否可寫System.out.println("判斷檔案是否可寫"+file.canWrite());//判斷檔案是否為檔案夾System.out.println("判斷檔案是否為檔案夾"+file.isDirectory());}}



4、檔案屬性的設定


主要內容包括將檔案設定為可讀、可寫或唯讀。

import java.io.File;import java.io.IOException;public class SetFileProperty {public static void main(String[] args) {File file = new File("text.file");if(file.exists()){System.out.println("檔案存在,不用建立!");//先確認檔案的屬性System.out.println("可讀嗎?"+file.canRead());System.out.println("可寫嗎?"+file.canWrite());System.out.println("可執行嗎?"+file.canExecute());//將檔案設定為可寫//file.setWritable(false);//true可寫false不可寫//將檔案設定為可讀//file.setReadable(false);//true可讀false不可讀//將檔案設定為唯讀file.setReadOnly();//再確認檔案的屬性System.out.println("\n");System.out.println("可讀嗎?"+file.canRead());System.out.println("可寫嗎?"+file.canWrite());System.out.println("可執行嗎?"+file.canExecute());}else{System.out.println("檔案不存在,請建立一個新檔案!");try {file.createNewFile();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}



5、遍曆檔案夾


主要內容包括通過使用listFiles()方法擷取檔案夾中的所有項目,並且通過遞迴顯示完整的層級結構。

package com.hqu.filetraverse.main;import java.io.File;public class Traverse {public static void main(String[] args) {printFiles(new File("/Job/Java/workspace/FileTraverse"),1);//使用絕對路徑//printFiles(new File("../FileTraverse"),1);//預設使用相對路徑}public static void printFiles(File dir,int tab) {if(dir.isDirectory()){File next[] = dir.listFiles();//傳回值是檔案和檔案夾,存在於數組中for(int i=0;i<next.length;i++){for(int j=0;j<tab;j++){//輸出|--當做識別層次的標記System.out.print("|--");//使用print而不是println,可以避免每次的換行}System.out.println(next[i].getName());//列印檔案或檔案夾的名字if(next[i].isDirectory()){printFiles(next[i],tab+1);//遞迴調用自身}}}}}



6、檔案的簡單讀寫


主要內容包括FileInputStream和FileOutputStream的使用方法,實現文字檔的讀取和寫出。

package com.hqu.rwfile;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;public class ReadFile {public static void main(String[] args) {File file = new File("text.txt"); //事先建立好,並輸入內容if(file.exists()){//System.out.println("exit");System.err.println("exit");//系統輸出try {//準備用於檔案輸入的三個流FileInputStream fis = new FileInputStream(file);//檔案的輸入資料流屬於位元組流InputStreamReader isr = new InputStreamReader(fis, "UTF-8");//InputStreamReader屬於字元流,"UTF-8"為指定文本編碼,防止亂碼BufferedReader br = new BufferedReader(isr);//帶有緩衝區的ReaderString line;//用於臨時存放讀取到的資料while((line = br.readLine()) != null){System.out.println(line);}//關閉輸入資料流br.close();isr.close();fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} }File newfile = new File("newtext.txt");//無需建立,寫入時系統自動建立檔案try {FileOutputStream fos = new FileOutputStream(newfile);OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");BufferedWriter bw = new BufferedWriter(osw);bw.write("abcd\n");bw.write("efgh\n");bw.write("ijkl\n");bw.write("mnop");//bw.write("長歌行 漢樂府");//bw.write("青青園中葵,朝露待日晞。\n");//bw.write("陽春布德澤,萬物生光輝。\n");//bw.write("常恐秋節至,焜黃華葉衰。\n");//bw.write("百川東到海,何時複西歸?\n");//bw.write("少壯不努力,老大徒傷悲!\n");bw.close();osw.close();fos.close();System.out.println("寫入完成!");} catch (FileNotFoundException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

JAVA學習(八):JAVA檔案編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.