2011-04-12 95 views
0

我正在使用此代码在SD卡的根目录中创建一个文件,但是,我有一个目录而不是“fileDir + fileName”!想要创建一个文件,而不是创建一个目录!

File file = new File(sdCard.getAbsolutePath(), fileDir+fileName); 
    if (!file.mkdirs()) { 

     Log.d("ERROR", "Create dir in sdcard failed"); 

     return; 
    } 
     OutputStream out = new FileOutputStream(file); 
.............................. 

谢谢您的帮助。

+0

因为这正是你告诉它使用file.mkdirs()? – 2011-04-12 00:39:55

回答

1

file.mkdirs()在if子句中生成目录结构。我可以测试你是否可以用file.canWrite()来写。

文档是here

既然你说,这是生成的目录,它应该返回true,但重要组成部分,这里没有显示:)

2

file.mkdirs()创建目录,而不是文件[编号:http://download.oracle.com/javase/1.4.2/docs/api/java/io/File.html#mkdir()。这是创建目录的代码。你应该使用这样的代码。

String destination = currentdir + "test.txt"; 
     File fileCon = new File(destination); 
     if(! fileCon.exists()){ 
       fileCon.createNewFile(); 
      } 

或者试试这个,

 String destination = currentdir + "test.txt"; 


// Open output stream 
      FileOutputStream fOut = new FileOutputStream(destination); 

      fOut.write("Test".getBytes()); 

      // Close output stream 
      fOut.flush(); 
      fOut.close(); 
+0

maked this:String destination = sdCard.getAbsolutePath()+ File.separator + fileDir + fileName; File fileCon = new File(destination);如果(!fileCon.exists()){ fileCon.createNewFile(); }总是同样的问题 – androniennn 2011-04-12 00:53:58

+0

尝试FileOutputStream中为你的旧的, //打开输出流 FileOutputStream中FOUT =新的FileOutputStream中(路径+ FNAME); fOut.write(“Test”.getBytes()); (关闭输出流 fOut.close(); – Priyank 2011-04-12 01:09:42

+0

像这样我不在文件中写入“Test”字符串? :\ – androniennn 2011-04-12 01:38:17

0

如果你希望file.mkdirs()创建该文件的目录,那么你需要稍微调整它file.getParentFile()。 mkdirs()

当然,这应该是包裹在一个try/catch子句,万一getParentFile()返回null

希望这有助于

Phil Lello

相关问题