<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
String path = "/mnt/sdcard/mydata/thaicreate.txt"; File file = new File(path); FileWriter writer = new FileWriter(file, true); //True = Append to file, false = Overwrite writer.write("String 1\n"); writer.write("String 2\n"); writer.close();
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="33dp" android:text="Input Yout Text" /> <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="27dp" android:ems="10" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_centerHorizontal="true" android:layout_marginTop="24dp" android:text="Save" /> </RelativeLayout>
package com.myapp; import java.io.File; import java.io.FileWriter; import java.io.IOException; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // editText1 final EditText txtInput = (EditText) findViewById(R.id.editText1); // button1 final Button btn1 = (Button) findViewById(R.id.button1); // Perform action on click btn1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { /*** Write Text File to SD Card ***/ try { String path = "/mnt/sdcard/mydata/thaicreate.txt"; File file = new File(path); /*** if exists create text file ***/ if(!file.exists()) { file.createNewFile(); } /*** Write Text File ***/ FileWriter writer = new FileWriter(file, true); //True = Append to file, false = Overwrite writer.write(txtInput.getText() + "\n"); writer.close(); Toast.makeText(MainActivity.this, "File Save!", Toast.LENGTH_LONG).show(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(MainActivity.this, "Failed! = " + e.getMessage() , Toast.LENGTH_LONG).show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท