31 AndroidがSdcardカードからデータを読み込む
1379 ワード
/**
* 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);
}