您的位置:首页 > 移动开发 > Android开发

31 Android 从Sdcard 卡 读取数据

2014-01-12 20:20 267 查看
/**
* 从Sdcard 卡 读取数据
* @param fileName
* @return
*/
public String readtextFromSdcard(String fileName)
{
File root=Environment.getExternalStorageDirectory();
FileInputStream inputStream=null;
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
String state=Environment.getExternalStorageState();
if(state.equals(Environment.MEDIA_MOUNTED))
{
File file=new File(root.getAbsolutePath()+"/txt");
File file2=new File(file, fileName);
int len=0;
byte[] data=new byte[1024];
if(file2.exists())
{
try {
inputStream=new FileInputStream(file2);
while ((len=inputStream.read(data)) != -1) {
outputStream.write(data, 0, len);
}
return new String(outputStream.toByteArray());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(outputStream != null)
{
try {
outputStream.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}

}

return null;
}


测试类中相关代码:

public void read() {
FileService service = new FileService();
String str = service.readtextFromSdcard("aa.txt");
System.out.println("------>>>>>>>" + str);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: