參考了Google上搜尋的結果以及偉大的API文檔
本樣本程式主要完成功能:
1,建立檔案夾及檔案
2,複製檔案,並顯示源檔案和複製檔案的修改時間和檔案名稱
主要用到的類及其方法:
java.io.File
java.io.FileInputStream
java.io.FileOutputStream
java.io.IOException
java.util.Date
java.text.DateFormat
File類的File(String),File(File,String),createNewFile,mkdirs,lastModified,isFile,isDirectory,exists方法
FileInputStream類的FileInputStream(File),read(byte[],int ,int)方法
FileOutputStream類的FileOutputStream(File),write(byte[],int,int)方法
Date類的Date(long)方法
DateFormat類的getDateInstance(),format(Date)方法
拋出IOException異常類即可
import java.io.File;<br />import java.io.IOException;<br />import java.io.FileInputStream;<br />import java.io.FileOutputStream;<br />import java.text.DateFormat;<br />import java.util.Date;<br />public class Test{<br />public static void main(String args[]) throws IOException{<br />System.out.println("Start.....");<br />String str1="hello.txt";//此處所示檔案可以存在,也可以不用存在<br />String dir="back//backup";//Attention: 兩個'/'<br />new Test().doIt(str1,dir);<br />System.out.println("Finished.....");<br />}<br />public void doIt(String str1,String dir) throws IOException{<br />//構造兩個檔案類<br />File f1=new File(str1);<br />File child=new File(dir);<br />//如果源檔案不存在,則建立一個檔案<br />if(!f1.exists()){<br />f1.createNewFile();<br />}<br />//如果要構建的目錄不存在,則建立一個目錄,其實是一個遞迴目錄<br />if(!child.exists())<br />child.mkdirs();<br />//構建目標檔案<br />File f2=new File(child,str1);<br />//如果目標檔案不存在,則建立一個檔案<br />if(!f2.exists())<br />f2.createNewFile();<br />//將檔案f1的內容,複製到檔案f2中<br />//不過此處類比Ctrl+C,Ctrl+V操作,並設定另外的目標檔案名<br />copy(f1,f2);<br />//擷取檔案或目錄中的檔案的資訊<br />getInfo(f1);<br />getInfo(f2);<br />}<br />public void copy(File f1,File f2) throws IOException{<br />//構建f1的輸入資料流,f2的輸出資料流<br />FileInputStream ifile=new FileInputStream(f1);<br />FileOutputStream ofile=new FileOutputStream(f2);<br />int count,n=512;<br />byte buf[]=new byte[n];<br />count=ifile.read(buf,0,n);<br />//如果read返回-1,則表明到達了檔案末尾<br />while(count!=-1){<br />ofile.write(buf,0,count);//Attention:第三個參數是count<br />count=ifile.read(buf,0,n);<br />}<br />//關閉輸入輸出資料流<br />ifile.close();<br />ofile.close();<br />}<br />public void getInfo(File file){<br />//如果file是檔案,則輸出其最後修改日期資訊和檔案絕對路徑名<br />if(file.isFile()){<br />System.out.println(DateFormat.getDateTimeInstance().format(new Date(file.lastModified()))+" "+file.getAbsolutePath());<br />}<br />//如果file是目錄,則取得目錄中的所有檔案,並列印其檔案的資訊<br />//如果目錄中仍有目錄,也可以遞迴調用<br />else if(file.isDirectory()){<br />File f[]=file.listFiles();<br />for(int i=0;i<f.length;i++)<br />getInfo(f[i]);<br />}<br />}<br />}