做为一个安卓菜鸟,我把自己学到的知识点尽量都放在博客里,以便以后温习,也可以为初学者们的一个小小参考。此博客为菜鸟所读,大神们敬请绕道哦![大笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif)
io简单操作
1、先上效果
代码具体实现如下:
package cjl.hycollege.com.inputtest;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class MainActivity extends AppCompatActivity {
TextView tv;
String filePath;
String filename="mytest.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv= (TextView) findViewById(R.id.textviews);
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Toast.makeText(this.getApplication(),"请插入SD卡",Toast.LENGTH_SHORT).show();
}else{
filePath= Environment.getExternalStorageDirectory().getAbsolutePath();
String infos="花花世界花花心\n花花男人没良心\n见到女就动心\n得到女人就变心!";
try {
writeStr(filePath,filename,infos);
} catch (Exception e) {
Toast.makeText(this.getApplication(),"写入失败",Toast.LENGTH_SHORT).show();
}
}
String rers=null;
try {
rers=readStr(filePath,filename);
tv.setText(rers);
} catch (Exception e) {
e.printStackTrace();
}
}
//读取数据
public String readStr(String filePath,String filename) throws Exception {
String res=null;
File file=new File(filePath,filename);
FileInputStream fis=new FileInputStream(file);
int leng=fis.available();
byte[] b=new byte[leng];
fis.read(b);
res= new String(b,"utf-8");
fis.close();
return res;
}
//写数据
public void writeStr(String filePath,String filename,String info) throws Exception {
File file=new File(filePath,filename);
FileOutputStream fop=new FileOutputStream(file);
byte[] b=info.getBytes();
fop.write(b);
fop.close();
}
}
新手注意:在操作SD卡进行读写时一个要在AndroidManifest.xml里配置SD卡读写权限(以后涉及到网络访问时也会有类似操作)。谨记!!!