Android 文件操作

1、获得系统根目录:

public String getDirPath(){
return Environment.getExternalStorageDirectory().getAbsolutePath();
}

2、创建目录:

public void mkdir(Context context, String path){

File filePath = new File(path);
if(!filePath.exists()){
   if(!filePath.mkdirs())
    Toast.makeText(
context,"创建目录失败", Toast.LENGTH_LONG).show();      
}

}

3、创建文件:

public void createFile(String filePath){

File file = new File(filePath);

if(!file.exists()){

try{

file.createNewFile();

}catch(IOException e){

}

}

}

4、写操作

/**
* 在指定位置写
* @param filename
* @param skipBytes
* @param data
* @return
*/
public static boolean writeData(String filepath,long skipBytes, String data){
boolean result = false;
File file = new File(filepath);
try{
RandomAccessFile rFile;
if(file.exists()){
rFile = new RandomAccessFile(file, "rw");
rFile.seek(skipBytes);
rFile.write(data.getBytes());
rFile.close();
rFile = null;
result = true;

}
}catch(Exception e){
// return result;
}
return result;
}

5、读操作

/**
* 读取指定位置的数据
* @param filename

 * @param offset

* @param readlen
* @return
*/
public String ReadData(String filename, long offset, int readlen){
String res=""; 
File file = new File(filename);
long fileLen = 0;
try{
RandomAccessFile rFile;
if(file.exists()){
rFile = new RandomAccessFile(file, "rw");
fileLen = rFile.length();

if(fileLen > offset+1){//读取位置必须在文件大小内
rFile.seek(offset);
byte[] data = new byte[readlen];
rFile.read(data);
res = EncodingUtils.getString(data, 0, readlen, "UTF-8"); 

}
rFile.close();
rFile = null;
}
}catch (Exception e) {
// TODO: handle exception
}
return res;
}

猜你喜欢

转载自blog.csdn.net/qq_27256793/article/details/78968873
今日推荐