文件编程


一.文件基础

 

随即读写文件

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();//程序退出后删除,只有正常退出才会删除  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值