经过这么多次尝试后,我无法为文件设置用户输入名称,并自动在末尾添加扩展名。所以在我的情况下,我有一个简单的.txt,我试图使用onClickListener保存我的文件。
通常它的工作方式如下:
public void onClick(View view) {
try {
FileOutputStream fout =
openFileOutput("filename_here.txt" , MODE_WORLD_READABLE);
但是我想让用户在这里设置一个个人标题,所以我在我的活动中提到了这个:
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Message = maintext.getText().toString();
try {
FileOutputStream fout = openFileOutput(title.getText().toString()+".txt" , MODE_WORLD_READABLE); //look at the extension .txt
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(Message);
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
我不知道是否可以通过这种方式添加扩展程序,但每当我按下保存按钮时,我的应用程序都会崩溃!
答案 0 :(得分:0)
我不得不手动将我的FileName放在onCreate void中,最后我添加了我的扩展名:
public class Save extends ActionBarActivity {
String FileName; //specify "FileName" as a string
EditText et; //and "et" as an EditText
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE);
final EditText maintext = (EditText) findViewById(R.id.test); //my main text where i put personal things.
et = (EditText) findViewById(R.id.save_filename); //assign et (EditText) to an object (or vice-versa). In this case, EditText is found in my XML with id save_filename
//Now setting onClickListener
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
//This line below make the trick
//We set a string, FileName, to contain a name we input in our "et" EditText and an extension added with the + ".txt" (note that there are no space before and after the .txt)
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "File Saved Successfully", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}