我确定对此有一个简单的答案,但我是新手,似乎无法弄清楚。
我需要将数据保存到文本文件中。我拥有执行此操作的所有代码,但路径和文件名目前是硬编码的。我有一个 EditText 字段,用户可以在其中输入文件名,然后点击一个按钮。我希望它根据用户输入的内容创建路径和文件名。
基本上是“/sdcard/”+Whateveruserentered.txt 的预先确定的路径
最佳答案
好的,这是一个简单的答案,
假设你在EditText中输入了“myPath/myfile.txt”,
首先您需要创建“myPath”文件夹(我假设您也在路径中提供了文件夹名称)。
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.
关于java - Android根据用户输入创建文件名路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12417205/