簡體   English   中英

如何在EditText中更改文件名

[英]How to change file name in edittext

我在網上找到了一些有趣的代碼。 然后將其復制粘貼到我的AIDEAndroid 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM