Write text from EditText to file - android
package com.getText.android;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
public class getText extends Activity {
public EditText ET;
public Button button1;
public String input;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ET = (EditText) findViewById(R.id.edittext);
ET.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
button1 = (Button)findViewById(R.id.btnClickMe);
button1.setOnClickListener(btnListener);
}
private OnClickListener btnListener = new OnClickListener(){
public void onClick(View v){
input = ET.getText().toString();
try{
File file = new File(Environment.getExternalStorageDirectory(), "fileOut.txt");
BufferedWriter writer = new Buf开发者_如何学运维feredWriter(new FileWriter(file,true));
writer.write(input);
writer.newLine();
writer.flush();
writer.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
}
The application runs just fine, but the file doesn't get created! Can someone tell me what's wrong? :)
I'm not sure if this is necessary, but have you tried to do:
file.createNewFile();
before creating the FileWriter
?
In general you should try to log your exceptions:
Log.e("getText", e.getMessage());
Unfortunately e.printStackTrace()
won't make it into logcat.
You should ask for permission to write to external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
See here: http://developer.android.com/guide/topics/manifest/uses-permission-element.html
精彩评论