java - Android根据用户输入创建文件名路径

标签 java android file

我确定对此有一个简单的答案,但我是新手,似乎无法弄清楚。

我需要将数据保存到文本文件中。我拥有执行此操作的所有代码,但路径和文件名目前是硬编码的。我有一个 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/

相关文章:

java - 在 Activity 之间传递数据

java - 默认情况下如何将 Maven 插件附加到阶段?

javascript - 通过 WebAuthn API 识别手指 ID

android - SQLite 联合列

java - 如何在应用程序中正确处理对文件的引用?

file - 保存 Windows XP 和 Vista 应用程序用户信息的最佳位置

java - 什么是 Floyd's_cycle_finding_algorithm 以及在哪里可以有效地使用它?

android - 我如何启动并绑定(bind)到 Android 中的服务?

python - 如何将png文件放入字符串并将其写入另一个文件

android - 在 View 组中添加 View 时忽略 layout_margin