android开发中的文件操作


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();

}

猜你喜欢

转载自japankn.iteye.com/blog/1722654