[英]How to change file name in edittext
我在网上找到了一些有趣的代码。 然后将其复制粘贴到我的AIDE
或Android IDE
。 到目前为止,它尚未检测到任何错误,但仅保存了我保存的所有文件中的一个文件名。 保存的旧文件将被更新的文件替换。
public class MainActivity extends Activity {
public EditText editText;
public TextView textView;
public Button save, load;
public String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFiles";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.edit);
textView = (TextView) findViewById(R.id.text);
save = (Button) findViewById(R.id.save);
File dir = new File(path);
dir.mkdirs();
}
public void buttonSave (View view)
{
File file = new File (path + "/saved.txt");
String [] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save (file, saveText);
}
}
public static void Save(File file, String[] data)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(file);
}
catch (FileNotFoundException e) {e.printStackTrace();}
try
{
try
{
for (int i = 0; i<data.length; i++)
{
fos.write(data[i].getBytes());
if (i < data.length-1)
{
fos.write("\n".getBytes());
}
}
}
catch (IOException e) {e.printStackTrace();}
}
finally
{
try
{
fos.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
我计划制作一个edittext
并将其命名为yourfilename
,在保存该名称后将使用它作为名称,以防止覆盖文件。 但是问题是我不知道在哪里添加代码以及那里是否有太多代码。 我对要使用的代码有疑问。 顺便说一下,我对此很陌生,所以我对此并不了解。 谢谢。
检查这是否对您有帮助。
public void buttonSave(View view) {
String fileName = editText.getText().toString();
File file = new File(path + "/" + fileName + ".txt");
String[] saveText = String.valueOf(editText.getText()).split(System.getProperty("line.separator"));
editText.setText("");
Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
Save(file, saveText);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.