2017-02-04 111 views
1

我试图在内部存储创建一个txt文件。 当我执行操作并调用负责创建文件的函数时,不会发生错误。但是,当我检查文件是否实际上是在/ data/data /文件夹中创建的时候,我找不到包含我的包名称的文件夹。试图保存并检查文件是否保存在内部存储

错误在哪里?

Ps .:我已经看到这方面的几个链接,但在所有情况下都是这种情况。

public void criarArq(Context mcoContext,String sFileName, String sBody){ 
    File file = new File(mcoContext.getFilesDir(),"mydir"); 
    if(!file.exists()){ 
     file.mkdir(); 
    } 

    try{ 
     File gpxfile = new File(file, sFileName); 
     FileWriter writer = new FileWriter(gpxfile); 
     writer.append(sBody); 
     writer.flush(); 
     writer.close(); 

    }catch (Exception e){ 

    } 
} 

我呼吁这样的功能...

criarArq(getApplicationContext(), arqNome, "teste"); 

谢谢所有帮助!

---更新---

现在这是我的代码:

try { 
      FileWriter writer = new FileWriter(gpxfile); 
      writer.append("teste"); 
      writer.flush(); 
      writer.close(); 
      Toast.makeText(InfoEntregasActivity.this, "created", 
        Toast.LENGTH_LONG).show(); 
     } catch (IOException e) { 
      //Don't eat the exception, do something with it, e.g. 
      Log.e("criarArq", e.toString()); //this will give you your error in the log cat 
      Toast.makeText(InfoEntregasActivity.this, e.toString(), 
        Toast.LENGTH_LONG).show(); 
      throw new RuntimeException(e); //this will bomb your program out for when the error is unrecoverable 
     } 

我尝试与不吐司(相同的结果),但与吐司我总是得到“创造”味精。

+1

你不应该忍气吞声例外。 'catch(Exception e){}'在适当的时候记录错误,恢复或崩溃。 –

+0

当您创建文件时,您看不到错误,因为您的“try ... catch”会忽略它。您应该更改'criarArq()'方法来声明可以抛出的异常,然后UI代码将有一个'try ... catch',它决定发生错误时应该怎么做。 –

+0

@ChristopherSchneider和Code-Apprentice,我已经解决了这个问题,但仍然处于相同的情况。感谢帮助。 “ – rponciano

回答

1

...没有发生错误

你吃任何潜在的异常,所以我就不会这么肯定。

public void criarArq(Context mcoContext, String fileName, String body) { 
    File file = new File(mcoContext.getFilesDir(),"mydir"); 
    file.mkdirs(); //no need to check exists with mkdirs 

    File gpxfile = new File(file, fileName); 
    try { 
     FileWriter writer = new FileWriter(gpxfile); 
     writer.append(body); 
     writer.flush(); 
     writer.close(); 
    } catch (IOException e) { 
     //Don't eat the exception, do something with it, e.g. 
     Log.e("criarArq", e.toString()); //this will give you your error in the log cat 
     throw new RuntimeException(e); //this will bomb your program out for when the error is unrecoverable 
    } 
} 

其他提示,mkdirs使得多层次并执行exists检查你。

请勿使用与类型相关的前缀,例如s...这是相当老派,约会现代IDEs。

要查看你的文件要

Log.d("criarArq", gpxfile.toString()); 
+0

我还在学习。感谢您的帮助!我明白你说的话,并调整了一切。然而,同样的情况仍在继续:没有发生错误。 我添加Toast消息进行测试,没有任何反应。 我用新功能更新了问题。 – rponciano

+1

我们都还在学习!不要相信说他们不是的人:D – weston

+0

使用Log.d(...)我可以看到文件路径。谢谢!我没有足够的声望投票= /,但你的答案是一个解决方案! – rponciano