1.AndroidManifest.xml加入權限
2./res/layout/activity_main.xml
3.Write.java
package tw.android; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import android.content.Context; import android.os.Environment; import android.util.Log; import android.widget.Toast; public class Write { private static Context context; public Write(Context context) { this.context = context; } public static void WriteFileExample(String message) { FileOutputStream fop = null; File file; String content = message; try { File sdcard = Environment.getExternalStorageDirectory(); file = new File(sdcard, context.getResources().getString(R.string.app_name)+"Log.txt"); //輸出檔案位置 Log.i("Write File:", file + ""); fop = new FileOutputStream(file); if (!file.exists()) { // 如果檔案不存在,建立檔案 file.createNewFile(); } byte[] contentInBytes = content.getBytes();// 取的字串內容bytes fop.write(contentInBytes); //輸出 fop.flush(); fop.close(); Toast.makeText(context, "輸出完成", Toast.LENGTH_LONG).show(); } catch (IOException e) { Log.i("Write E:", e + ""); e.printStackTrace(); } finally { try { if (fop != null) { fop.close(); } } catch (IOException e) { Log.i("Write IOException", e + ""); e.printStackTrace(); } } } }4.MainActivity.java
package tw.android; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private EditText etWrite; private Button btWrite; private Write write = new Write(MainActivity.this); /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etWrite = (EditText) findViewById(R.id.etWrite); btWrite = (Button) findViewById(R.id.btWrite); btWrite.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { write.WriteFileExample(etWrite.getText().toString()); // 寫入輸入文字 } }); } }
檔案下載:
https://github.com/terryyamg/WriteFileTest
參考連結:
http://www.mkyong.com/java/how-to-write-to-file-in-java-fileoutputstream-example/
沒有留言 :
張貼留言