2016-11-18 107 views
-1

我想开发一个程序,在特定的目录(.txt文件)中创建一个文件并在其中存储一些数据(例如字符串)。我也希望文件可以被用户访问(如果我去文件资源管理器,我可以查看我创建的文件,也可以用另一个程序或其他东西编辑它)。如何在Android中的特定目录中创建.txt文件?

我试过很多东西,但是我无法管理这个工作。

这里是我使用ATM代码:

public void createFile(View view) throws IOException { 

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd"); 
    Date now = new Date(); 
    String fileName = formatter.format(now) + ".txt"; 
    String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Sonda Drive Test"; 

    File mypath = new File(filepath); 
    if(!mypath.exists()) { 
     mypath.mkdir(); 
    } 
    //now the mkdir returns true isntead of false 


    File myfile = new File(mypath, fileName); 

    try{ 
     if(!myfile.exists()){ 
      txtDebug.setText("Não existe ficheiro!"); 
      myfile.createNewFile(); 
     } 
     else{ 
      txtDebug.setText("Já existe ficheiro!"); 
     } 
    }catch (Exception e){ 
     txtDebug.setText("Erro!"); 
    } 
} 

我还添加权限波纹管:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

的问题是,当我做

myfile.createNewFile(); 

应用程序停止并关闭..但如果我评论该行,它也不会创建任何文件...

我在做什么错?

编辑:我管理使这个工作的API 22.我怎么能做到API 25?

+1

'程序Crashes'究竟你是什么意思?你有什么异常/堆栈跟踪?请[编辑] int LogCat的详细日志输出。由于缺乏背景而投票结束。 –

+0

'mypath.mkdir();'。检查返回值,因为它可能无法创建目录。如果它返回false,则向用户显示敬酒,并返回。 – greenapps

+0

您可能会因为“myfile”不存在而需要检查该文件是否存在if(!myfile.exists()) –

回答

0

你把mypath中的路径,但你定义为mypath中文件

+0

好吧,那么我如何将mypath定义为路径呢? –

+0

布鲁诺不听布鲁诺。 – greenapps

+0

@greenapps哈哈,好的 –

相关问题