展会信息港展会大全

Android的file文件操作详解 android开发
来源:互联网   发布日期:2016-01-19 12:23:00   浏览:2937次  

导读:android的文件操作要有权限:判断SD卡是否插入Environment getExternalStorageState() equals(android os Environment MEDIA_MOUNTED);获得sd卡根目录File skRoot = Environment getExternalStorageDirectory ...

android的文件操作要有权限:

判断SD卡是否插入

Environment.getExternalStorageState().equals(

android.os.Environment.MEDIA_MOUNTED);

获得sd卡根目录

File skRoot = Environment.getExternalStorageDirectory();

获得私有根目录

File fileRoot = Context.getFilesDir()+"";

确定或获得文件夹和文件路径

String path = File.getPath();//相对

String path = File.getAbsoultePath();//绝对

获得文件或文件夹的父目录

String parentPath = File.getParent()

获得文件或文件夹的名称:

String Name = File.getName();

建立文件或文件夹

File.createNewFile();//建立文件

判断是文件或文件夹

File.isDirectory()

列出文件夹下的所有文件和文件夹名

File[] files = File.listFiles();

修改文件夹和文件名

File.renameTo(dest);

删除文件夹或文件

File.delete();

文件读写操作模式

Context.MODE_PRIVATE:新内容覆盖原内容

Context.MODE_APPEND:新内容追加到原内容后

Context.MODE_WORLD_READABLE:允许其他应用程序读取

Context.MODE_WORLD_WRITEABLE:允许其他应用程序写入,会覆盖原数据。

/*** 保存文件

* @param fileName

* @param fileContent

* @throws Exception*/

public void save(String fileName, String fileContent) throws Exception {

// Activity的父类的父类就是context,context与其他框架中的context相同为我们以供了一些核心操作工具。

FileOutputStream fileOutputStream = this.context.openFileOutput(

fileName, Context.MODE_PRIVATE);

fileOutputStream.write(fileContent.getBytes());

}

/**

* 读取文件

*

* @param fileName

* @return

* @throws Exception

*/

public String read(String fileName) throws Exception {

FileInputStream fileInputStream = this.context.openFileInput(fileName);

ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];

int len = 0;

while ((len = fileInputStream.read(buffer)) > 0) {

byteArray.write(buffer, 0, len);

};

return byteArray.toString();

}

}

赞助本站

人工智能实验室

相关热词: file 文件操作 android开发

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港