我确信有一个简单的答案,但我是新的,似乎无法解决这个问题。
我需要将数据保存到文本文件中。我有所有代码,但路径和文件名现在是硬编码的。我有一个EditText字段,用户输入文件名,然后点击一个按钮。我希望它根据用户输入的内容创建路径和文件名。
基本上是预先确定的路径" / sdcard /" + Whateveruserentered.txt
答案 0 :(得分:1)
好的,这是一个简单的答案,
假设您已在EditText中输入“myPath / myfile.txt”,
首先,您需要创建“myPath”文件夹(我假设您在路径中也提供了foldername)。
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.