【问题标题】:Android creating a filename path from user inputAndroid从用户输入创建文件名路径
【发布时间】:2012-09-14 02:02:51
【问题描述】:

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

我需要将数据保存到文本文件。我有所有的代码来做到这一点,但路径和文件名现在是硬编码的。我有一个 EditText 字段,用户在其中输入文件名,然后点击一个按钮。我希望它根据用户输入的内容创建路径和文件名。

基本上是“/sdcard/”+Whateveruserentered.txt的预设路径

【问题讨论】:

  • 只需获取用户在您设置的EditText 中输入的任何值,将其转换为字符串并使用+ 运算符将其添加到文件路径名中。 EditText filename = new EditText(this); filename.getText().toString();

标签: java android file


【解决方案1】:

好的,这里是一个简单的答案,

假设你在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.

【讨论】:

  • 太棒了!我已经定义了路径,但有效的是使用您的第一行并将其更改为我的需要: String filename =edittextfield.getText().toString().trim();非常感谢!
猜你喜欢
  • 2012-03-30
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多