我有一個需要讀取和寫入文本文件的應用程序。我讀它,但我沒有寫它。這個想法是,當我點擊屏幕上的保存按鈕時,它將把放入文本視圖的所有信息保存到一個數組中,並將數組的每一段寫入文本文件。這是我寫作部分代碼:如何在Android中寫入.txt文件?
public class AddOrModify extends Activity {
private Button Savebtn;
private Button Cancelbtn;
private EditText NameofRoute;
private EditText Address1;
private EditText City1;
private EditText State1;
private EditText Zip1;
private EditText Address2;
private EditText City2;
private EditText State2;
private EditText zip2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_or_modify);
Savebtn = (Button)findViewById(R.id.savebtn);
Savebtn.setOnClickListener(new btnlistenersave());
Cancelbtn = (Button)findViewById(R.id.cancelbtn);
Cancelbtn.setOnClickListener(new btnlistenercancel());
}
private class btnlistenersave implements View.OnClickListener{
public void onClick(View v) {
NameofRoute = (EditText)findViewById(R.id.NameofRoute);
Address1 = (EditText)findViewById(R.id.editAddress1);
City1 = (EditText)findViewById(R.id.City1);
State1= (EditText)findViewById(R.id.State1);
Zip1 = (EditText)findViewById(R.id.Zip1);
Address2= (EditText)findViewById(R.id.Address2);
City2 = (EditText)findViewById(R.id.City2);
State2 = (EditText)findViewById(R.id.State2);
zip2 = (EditText)findViewById(R.id.Zip2);
//String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};
// if(mySettings != null){
try{
String NameofRouteinput = NameofRoute.getText().toString();
String Address1input = Address1.getText().toString();
String City1input = City1.getText().toString();
String State1input=State1.getText().toString();
String Zip1input = Zip1.getText().toString();
String Address2input =Address2.getText().toString();
String City2input = City2.getText().toString();
String State2input = State2.getText().toString();
String Zip2input= zip2.getText().toString();
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("myaddress.txt",0));
String[] mySettings ={NameofRouteinput,Address1input,City1input, State1input,Zip1input,Address2input,City2input,State2input,Zip2input,";"};
for(int i =0; i < mySettings.length; i++)
out.write(mySettings[i]);
out.close();
}
catch (java.io.IOException e){
}
Intent i = new Intent(AddOrModify.this, Frontpage.class);
startActivity(i);
}
}
private class btnlistenercancel implements View.OnClickListener{
public void onClick(View v) {
Intent i = new Intent(AddOrModify.this, Frontpage.class);
startActivity(i);
}
}
}
我能做到這一點了整個數組雖然?你的例子讓我寫一個字符串,我需要爲許多值做這件事,或者我將不得不單獨做它們? –
是的,也應該工作...我爲你更新了答案。我希望我能幫上忙。 – mari
「數據」區域應該做什麼?我試着把一個字符串,一個字符串數組和其他一些東西放在那裏。要麼它給我一個錯誤,要麼讓所有其他行都得到一個IOException。 –