首先需要设置权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MainActivity.java:
package com.miao.storetosdcard;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends AppCompatActivity {
private File file;
private OutputStream os;
private InputStream is;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取sdcard的绝对路径:Environment.getExternalStorageDirectory().getAbsolutePath()
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/john.data");
}
public void store(View view) throws Exception{
os = new FileOutputStream(file);
os.write("Hello World , 你好世界。\n".getBytes("utf-8"));
os.close();
}
public void read(View view) throws Exception{
is = new FileInputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
String content = new String(data,"utf-8");
Log.i("miao",content);
is.close();
}
}