简体   繁体   中英

How to change file name in edittext

I found some interesting codes online. And I copy paste it into my AIDE or Android IDE . It hasn't detected any error so far but it just only saves in one file name in all files I saved. And the older file saved will be replaced by a newer one.

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();}
    }
}

I am planning to make an edittext and name it as yourfilename and that will be its name after I saved it to prevent overwriting files. But the problem is I don't know where to add codes and for so many codes there. I am having doubt of which codes to be used. By the way, I am very new to this so I do not know much about it. Thank you.

Check if this helps you.

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM