添加扩展手动imputted文件名 [英] Add extension to a manually imputted filename
问题描述
这么多的尝试后,我一直没有用户输入的名称设置为一个文件,并自动把扩展名结尾。因此,在我来说,我有一个简单的txt文件,我想用onClickListener保存我的文件。
After so many attempts, I've failed to set a user input name to a file and automatically put an extension at the end. So in my case I have a simple .txt, I'm trying to save my file using onClickListener.
通常情况下它会工作,如:
Normally it would work like:
public void onClick(View view) {
try {
FileOutputStream fout =
openFileOutput("filename_here.txt" , MODE_WORLD_READABLE);
但我想,让用户设置个人的标题在这里,所以我这在我的活动:
But I'd like to let the user set a personal title here, so I've this in my Activity:
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();
}
}
});
我不知道,如果这种方式来添加一个扩展可能的,但每当我打保存按钮我的应用程序崩溃!
I don't know if this way to add an extension is possible but whenever I hit the save button my app crash!
推荐答案
我不得不手动把我的文件名在OnCreate无效,在其中我将自己的扩展结束:
I had to manually put my FileName in the onCreate void, at the end of which I added my extension:
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();
}
这篇关于添加扩展手动imputted文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!