文件編程


一.文件基礎

 

隨即讀寫文件

RandomAccessFile

 

3.IO

目的:提高IO速度

原理:通過通道和緩衝器來實現快速IO讀寫,通道依靠緩衝器實現高速緩衝讀寫

主要類及之間關係:

FileChannel:用於通道讀寫的通道

ByteBuffer:直接與通道交互的緩衝器,視圖緩衝器以此爲基礎,通過asCharBuffer等實現視圖緩衝。通過flip()爲讀取buffer中的數據做準備

注:flip()作用:將buffer的位置指針歸零,使得可以從buffer中最開始讀取。

FileInputStream:

FileOutputStream:

RandomAccessFile:用於產生FileChannel,通過getChannel()方法

 

視圖緩衝器:

IntBuffer|LongBuffer|CharBuffer|ShortBuffer....

 

連接通道

channel.transferTo()||transferFrom()

數據轉換

1.通過ByteBufferasXXXBuffer()可以將ByteBuffer轉換成對應的類型

2.通過CharsetByteBuffer的字節數據進行編碼和解碼

大小端

ByteBuffer使用的是大端模式,即數據高位存於地址低位

緩衝器的細節

1.mark:一個標記作用

2.mark():設置標記

3.reset():將當前位置(position)設置成標記(mark)的值

存儲器映射文件

MappedByteBuffer

1.通過channel.map(MapMode,position,size)獲取映射字節緩衝

注:映射文件的輸出必須使用RandomAccessFile

性能比較

映射文件訪問的效率比其他訪問塊很多

加鎖

1.加鎖

tryLock():如果不能獲得鎖則直接返回

lock():如果不能獲得鎖則一直等待

2.解鎖

release():釋放鎖

解壓縮

Zipgzip

解壓

ZipZipInputStream

GZip:GZIPInputStream

壓縮:

Zip:ZipOutputStream

GZIP:GZipOutputStream

二.路徑

1.Android文件路徑格式

1)Sdcard

file://+filePath

例如:“file://sdcard/DoWeather/download/DoItWeatherForcast.apk

1)獲取文件的路徑

file:///sdcard/...

public  void makeDir(String dirName) throws IOException {

// TODO Auto-generated method stub

String newPath = path+dirName;

File dir = new File(newPath);

if(!dir.exists())

dir.mkdirs();

}

 

 

二.文件創建

public  void createFile(String subName,String fileName) throws IOException{

String newPath = path+subName;

File dir = new File(newPath);

if(!dir.exists())

dir.mkdirs();

//makeDir(subName);

String filePath = newPath+"/"+fileName;

File file = new File(filePath);

boolean s ;

if(!file.exists()){

s = file.createNewFile();

}

FileOutputStream fos = new FileOutputStream(file);

fos.write("hellow".getBytes());

fos.close();

}

 

三.讀寫文件

寫文件

1.利用FileWriter(File,boolean)實現

2.在使用fw.write(content);

public static void addContentToFile(String subName,String fileName,String content) throws IOException {

// TODO Auto-generated method stub

String newPath = path+subName;

File dir = new File(newPath);

if(!dir.exists())

dir.mkdirs();

//makeDir(subName);

String filePath = newPath+"/"+fileName;

File file = new File(filePath);

if(!file.exists())

file.createNewFile();

FileWriter fw = new FileWriter(file,true);//將第二個參數設爲true則表示允許添加到文件尾部

fw.write(content);

fw.close();

}

 

3.FileOutputStream連續寫文件

public static void createNewFile(String subName,String fileName,InputStream is) throws IOException {

// TODO Auto-generated method stub

String newPath=null;

//newPath = pathInside+Environment.getRootDirectory();

if(isSdCardExists())

newPath = path+subName;

else

newPath = pathInside+subName;

File dir = new File(newPath);

if(!dir.exists())

dir.mkdirs();

//makeDir(subName);

String filePath = newPath+"/"+fileName;

File file = new File(filePath);

if(!file.exists())

file.createNewFile();

//FileWriter fw = new FileWriter(file,true);

FileOutputStream fos = new FileOutputStream(file);

byte[]buffer = new byte[1024];

int readByte  =0;

do{

readByte = is.read(buffer);//寫入buffer,返回結果是所讀字節數

if(readByte==-1){//文件讀完了

break;

}

fos.write(buffer, 0, readByte);

UpdateUtils.downloadLen+=readByte;

Log.d(tag"curLength:"+UpdateUtils.downloadLen+",完成:"+(UpdateUtils.downloadLen/UpdateUtils.len) * 100+"%");

}while(true);

//fw.write(content);

try{

//installAPK();

fos.close();

}catch(Exception e){Log.e(tag, e.toString());}

}

讀文件

/**

 * 讀取文件

 * @param subName

 * @param fileName

 * @return

 * @throws IOException

 */

public static String readFile(String subName,String fileName) throws IOException {

// TODO Auto-generated method stub

String newPath="";

//newPath = pathInside+Environment.getRootDirectory();

if(subName ==null)

subName = "";

if(isSdCardExists())

newPath = path+subName;

String filePath = newPath+"/"+fileName;

File file = new File(filePath);

BufferedReader br = new BufferedReader(new FileReader(file));

StringBuffer sb = new StringBuffer();

String content;

while((content=br.readLine())!=null){

sb.append(content);

}

return sb.toString();

}

 

基礎知識

此爲網上找的另一博主的文章

(一)獲取總根


File[] fileList=File.listRoots();  

//返回fileList.length爲1  

//fileList.getAbsolutePath()爲"/"  

//這就是系統的總根  

File[] fileList=File.listRoots(); //返回fileList.length爲1 //fileList.getAbsolutePath()爲"/" //這就是系統的總根

(二)打開總根目錄


File file=new File("/");  

File[] fileList=file.listFiles();  

//獲取的目錄中除了"/sdcard"和"/system"還有"/data"、"/cache"、"/dev"等  

//Android的根目錄並不像Symbian系統那樣分爲C盤、D盤、E盤等  

//Android是基於Linux的,只有目錄,無所謂盤符  

File file=new File("/"); File[] fileList=file.listFiles(); //獲取的目錄中除了"/sdcard"和"/system"還有"/data"、"/cache"、"/dev"等 //Android的根目錄並不像Symbian系統那樣分爲C盤、D盤、E盤等 //Android是基於Linux的,只有目錄,無所謂盤符

(三)獲取系統存儲根目錄


10 File file=Environment.getRootDirectory();//File file=new File("/system");  

11 File[] fileList=file.listFiles();  

12 //這裏說的系統僅僅指"/system"  

13 //不包括外部存儲的手機存儲的範圍遠遠大於所謂的系統存儲  

File file=Environment.getRootDirectory();//File file=new File("/system"); File[] fileList=file.listFiles(); //這裏說的系統僅僅指"/system" //不包括外部存儲的手機存儲的範圍遠遠大於所謂的系統存儲

(四)獲取SD卡存儲根目錄


14 File file=Environment.getExternalStorageDirectory();//File file=new File("/sdcard");  

15 File[] fileList=file.listFiles();  

16 //要獲取SD卡首先要確認SD卡是否裝載  

17 boolean is=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);  

18 //如果true,則已裝載  

19 //如果false,則未裝載  

File file=Environment.getExternalStorageDirectory();//File file=new File("/sdcard"); File[] fileList=file.listFiles(); //要獲取SD卡首先要確認SD卡是否裝載 boolean is=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //如果true,則已裝載 //如果false,則未裝載

(五)獲取data根目錄

20 File file=Environment.getDataDirectory();//File file=new File("/data");  

21 File[] fileList=file.listFiles();  

22 //由於data文件夾是android裏一個非常重要的文件夾,所以一般權限是無法獲取到文件的,即fileList.length返回爲0  

File file=Environment.getDataDirectory();//File file=new File("/data"); File[] fileList=file.listFiles(); //由於data文件夾是android裏一個非常重要的文件夾,所以一般權限是無法獲取到文件的,即fileList.length返回爲0

(六)獲取私有文件路徑


23 Context context=this;//首先,在Activity裏獲取context  

24 File file=context.getFilesDir();  

25 String path=file.getAbsolutePath();  

26 //此處返回的路勁爲/data/data/包/files,其中的包就是我們建立的主Activity所在的包  

27 //我們可以看到這個路徑也是在data文件夾下  

28 //程序本身是可以對自己的私有文件進行操作  

29 //程序中很多私有的數據會寫入到私有文件路徑下,這也是android爲什麼對data數據做保護的原因之一  

Context context=this;//首先,在Activity裏獲取context File file=context.getFilesDir(); String path=file.getAbsolutePath(); //此處返回的路勁爲/data/data/包/files,其中的包就是我們建立的主Activity所在的包 //我們可以看到這個路徑也是在data文件夾下 //程序本身是可以對自己的私有文件進行操作 //程序中很多私有的數據會寫入到私有文件路徑下,這也是android爲什麼對data數據做保護的原因之一

(七)獲取文件(夾)絕對路徑、相對路勁、文件(夾)名、父目錄


30 File file=……  

31 String relativePath=file.getPath();//相對路徑  

32 String absolutePath=file.getAbsolutePath();//絕對路徑  

33 String fileName=file.getName();//文件(夾)名  

34 String parentPath=file.getParent();//父目錄  

File file=…… String relativePath=file.getPath();//相對路徑 String absolutePath=file.getAbsolutePath();//絕對路徑 String fileName=file.getName();//文件(夾)名 String parentPath=file.getParent();//父目錄

(八)列出文件夾下的所有文件和文件夾


35 File file=……  

36 File[] fileList=file.listFiles();  

File file=…… File[] fileList=file.listFiles();

(九)判斷是文件還是文件夾


37 File file=……  

38 boolean is=file.isDirectory();//true-是,false-否  

File file=…… boolean is=file.isDirectory();//true-是,false-否

(十)判斷文件(夾)是否存在


39 File file=……  

40 boolean is=file.exists();//true-是,false-否  

File file=…… boolean is=file.exists();//true-是,false-否

(十一)新建文件(夾)


41 File file=……  

42 oolean is=file.isDirectory();//判斷是否爲文件夾  

43 /*方法1*/  

44 if(is){  

45     String path=file.getAbsolutePath();  

46     String name="ABC";//你要新建的文件夾名或者文件名  

47     String pathx=path+name;  

48     File filex=new File(pathx);  

49     boolean is=filex.exists();//判斷文件(夾)是否存在  

50     if(!is){  

51         filex.mkdir();//創建文件夾  

52         //filex.createNewFile();//創建文件  

53     }  

54 /*方法2*/  

55 if(is){  

56     String path=file.getAbsolutePath();  

57     String name="test.txt";//你要新建的文件夾名或者文件名  

58     File filex=new File(path,name);//方法1和方法2的區別在於此  

59     boolean is=filex.exists();//判斷文件(夾)是否存在  

60     if(!is){  

61         filex.mkdir();//創建文件夾  

62         //filex.createNewFile();//創建文件  

63 }  

File file=…… oolean is=file.isDirectory();//判斷是否爲文件夾 /*方法1*/ if(is){ String path=file.getAbsolutePath(); String name="ABC";//你要新建的文件夾名或者文件名 String pathx=path+name; File filex=new File(pathx); boolean is=filex.exists();//判斷文件(夾)是否存在 if(!is){ filex.mkdir();//創建文件夾 //filex.createNewFile();//創建文件 } /*方法2*/ if(is){ String path=file.getAbsolutePath(); String name="test.txt";//你要新建的文件夾名或者文件名 File filex=new File(path,name);//方法1和方法2的區別在於此 boolean is=filex.exists();//判斷文件(夾)是否存在 if(!is){ filex.mkdir();//創建文件夾 //filex.createNewFile();//創建文件 }

(十二)重命名文件(夾)


64 File file=……  

65 String parentPath=file.getParent();  

66 String newName="name";//重命名後的文件或者文件夾名  

67 File filex=new File(parentPath,newName);//File filex=new File(parentPaht+newName)  

68 file.renameTo(filex);  

File file=…… String parentPath=file.getParent(); String newName="name";//重命名後的文件或者文件夾名 File filex=new File(parentPath,newName);//File filex=new File(parentPaht+newName) file.renameTo(filex);

(十三)刪除文件(夾)


69 File file=……  

70 file.delete();//立即刪除  

71 //file.deleteOnExit();//程序退出後刪除,只有正常退出纔會刪除  

 

發佈了30 篇原創文章 · 獲贊 1 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章