public class MainActivity extends Activity { private static final String FILENAME = "/sdcard/wyt/wei.txt"; //设置文件名称 private TextView msg;
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); msg = (TextView) findViewById(R.id.msg); 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 (file != null ) { out.close(); } } }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
}
千万别忘了加权限啊
2.从SD卡读取文件
package com.example.fileoperate;
import java.io.File;
public class MainActivity extends Activity { private static final String FILENAME = "wei.txt"; //设置文件名称 private static final String DIR = "wyt"; private TextView msg;
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); msg = (TextView) findViewById(R.id.msg); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ File file = new File(Environment.getExternalStorageDirectory()+File.separator+DIR+File.separator+FILENAME); if(!file.getParentFile().exists()){ file.getParentFile().mkdirs(); }
// PrintStream out = null; Scanner scan = null; try { scan = new Scanner(new FileInputStream(file)); while (scan.hasNext()) { msg.append(scan.next()+"\n"); }
// out = new PrintStream(new FileOutputStream(file));
// out.println("移动未来:爱德华"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if (file != null ) { scan.close(); } } }else{ Toast.makeText(this, "没有内存卡", Toast.LENGTH_LONG).show(); } }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; }