Android SD卡读取简单操作
Posted 学无止境
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android SD卡读取简单操作相关的知识,希望对你有一定的参考价值。
package com.example.sdcardtest; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.RandomAccessFile; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { final String FILE_NAME = "/baidu/hello.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button read = (Button) findViewById(R.id.read); Button write = (Button) findViewById(R.id.write); final EditText edit1 = (EditText) findViewById(R.id.editText1); final EditText edit2 = (EditText) findViewById(R.id.editText2); //为write事件绑定监听器 write.setOnClickListener(new OnClickListener() { public void onClick(View v) { write(edit1.getText().toString()); edit1.setText(""); } }); //为read事件绑定监听器 read.setOnClickListener(new OnClickListener() { public void onClick(View v) { edit2.setText(read()); } }); } public String read(){ if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File sdCardDir = Environment.getExternalStorageDirectory(); try { FileInputStream fis = new FileInputStream(sdCardDir.getCanonicalPath() + FILE_NAME); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); StringBuilder sb = new StringBuilder(""); String line = null; while( (line = br.readLine()) != null ){ sb.append(line); } br.close(); return sb.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } public void write(String content){ if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ RandomAccessFile raf = null; try { //获取sd卡的目录 File sdCardDir = Environment.getExternalStorageDirectory(); File targetFile = new File(sdCardDir.getCanonicalFile() + FILE_NAME); raf = new RandomAccessFile(targetFile, "rw"); raf.seek(targetFile.length()); raf.write(content.getBytes()); } catch (IOException e) { e.printStackTrace(); } try { raf.close(); } catch (IOException e) { e.printStackTrace(); } } } } ===================== 布局文件 简单的两个按钮,没什么好说的
以上是关于Android SD卡读取简单操作的主要内容,如果未能解决你的问题,请参考以下文章
android如何读取sd卡目录文件夹下多个文件,自定义一个case文件夹,如何读取里面的多个文件