package com.example.filedemo1; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import android.os.Bundle; import android.app.Activity; public class MainActivity extends Activity { private static final String FILENAME = "/mnt/sdcard/neusoft/jmz.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); File file = new File(FILENAME); //判断文件是否存在,如果不存在创建 if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); } PrintStream out = null; try { out = new PrintStream(new FileOutputStream(file)); out.println("中国吉林长春"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(out!=null){ out.close(); } } } }
必须配置权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
tv = (TextView) findViewById(R.id.tv); // 判断sd卡是否挂载 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 得到sd卡名称 File file = new File(Environment.getExternalStorageDirectory() + File.separator + DIR + File.separator + FILENAME); Scanner sc = null; try { //判断文件是否存在 if (file.getParentFile().exists()) { sc = new Scanner(new FileInputStream(file)); while (sc.hasNext()) { tv.append(sc.next()); } }else{ Toast.makeText(this, "不存在", 0).show(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (sc != null) { sc.close(); } } } else { Toast.makeText(this, "不存在sd卡", 0).show(); }
时间: 2024-10-07 01:52:44