1

I'm sure there is a simple answer to this but I'm new and can't seem to figure this out.

I need to save data to a text file. I have all the code to do that but the path and filename is hard-coded for now. I have an EditText field where the user enters the filename and then hits a button. I want it to create a path and filename based on what the user enters.

Basically a pre determined path of "/sdcard/"+Whateveruserentered.txt

1
  • Just get the value of whatever the use enters in the EditText you set up, turn it into a string and use the + operator to add it to file pathname. EditText filename = new EditText(this); filename.getText().toString(); Commented Sep 14, 2012 at 2:14

1 Answer 1

1

Ok , here is a simple answer,

suppose you have entered "myPath/myfile.txt" in EditText,

First you need to create "myPath" folder ( I am assuming you are giving foldername too in path ).

String fullPath = myEditText.getText().toString().trim();
String folderPath = fullPath.substring ( 0, fullPath.indexOf ( "/" ) );
String fileName = fullPath.substring ( fullPath.indexOf ( "/" ) + 1 );

// First Create folder by coding, 

File folder = new File(Environment.getExternalStorageDirectory().toString() + folderPath );
if (!folder.exists()) 
{
      folder.mkdirs();
}

// Note: your path must not have recursive folders like myPath1/myPath2/myFile.txt, otherwise you need to create folder in 2 steps.

// Now creating file
File file = new File(Environment.getExternalStorageDirectory().toString() + folderPath + fileName );

if ( !file.exists() )
{
    success = file.createFile();
}

// Now your file is created, you can do writing code now onwards.
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I already had the path defined but what worked was using your first line and changing it to my needs: String filename =edittextfield.getText().toString().trim(); Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.