FileOutputStream output=null; try { output=openFileOutput("1.txt", MODE_PRIVATE); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } PrintStream print=new PrintStream(output); print.println("姓名:DanielHan"); print.println("年龄:10"); print.close();
二.读
private TextView txt=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txt=(TextView)findViewById(R.id.txt); FileInputStream input=null; try { input=openFileInput("1.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Scanner scanner=new Scanner(input); while(scanner.hasNext()){ txt.append(scanner.next()+"\n"); } scanner.close(); }
结果:
三.向sdcard写
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File file=new File(Environment.getExternalStorageDirectory()+File.separator+"files/2.txt"); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } PrintStream print=null; try { print = new PrintStream(new FileOutputStream(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } print.println("姓名:DanielHan"); print.println("年龄:10"); print.close(); }else{ Toast.makeText(this, "没有sdcard",Toast.LENGTH_SHORT).show(); }