androidSD卡中文件的读写操作

//写入到SD卡

@SuppressLint("SdCardPath")

public void writeToFile(){

File file = new File(Environment.getExternalStorageDirectory(), "eboy.txt");


         OutputStream os = null;

         

         String str = "hello boy";

         try {

             os = new FileOutputStream(file);

             os.write(str.getBytes());

             os.flush();

             os.close();

         } catch (FileNotFoundException e) {

             e.printStackTrace();

         } catch (IOException e) {

e.printStackTrace();

}

        

         Toast.makeText(MainActivity.this, "写文件到SD卡成功。eboy.txt", Toast.LENGTH_SHORT).show();

}



//从SD卡文件中读取数据

@SuppressWarnings("resource")

public String readFromFile(){

 

String res = null;

 

byte[] buff = null;

 

File file = new File(Environment.getExternalStorageDirectory(),"eboy.txt");

 

InputStream in = null;

 

try {

in = new FileInputStream(file);

int length = in.available();

buff = new byte[length];

in.read(buff);

res = EncodingUtils.getString(buff, "GBK");

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return res;

}

//最后别忘了在manifest下添加权限

 

 


请尊重原创: http://control.blog.sina.com.cn/admin/article/article_add.php


你可能感兴趣的:(SD卡操作)