xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="100dp" android:hint="请输入文字" android:textColor="#000000" android:gravity="left|top" /> <Button android:id="@+id/sdsave" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="sd储存" /> <Button android:id="@+id/save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="内部存储" /> </LinearLayout>
import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; public class MainActivity extends AppCompatActivity { private EditText editText; private Button save; private Button sdsave; File file; final String fileName = "data.txt"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText = (EditText) findViewById(R.id.editText); save = (Button) findViewById(R.id.save); sdsave = (Button) findViewById(R.id.sdsave); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileOutputStream fos = null; String text = editText.getText().toString(); try { fos = openFileOutput(fileName,MODE_PRIVATE); fos.write(text.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { fos.close(); Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); } } } }); file = new File(Environment.getExternalStorageDirectory(),"Text.txt"); sdsave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FileOutputStream fos = null; String text = editText.getText().toString(); try { Toast.makeText(MainActivity.this,"sd卡不可用,请点击内部存储按钮",Toast.LENGTH_SHORT).show(); fos = new FileOutputStream(file); fos.write(text.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (fos != null){ fos.close(); Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_SHORT).show(); } } catch (IOException e) { e.printStackTrace(); } } } }); } }