2010-01-17 1150 views
3

我發現,你可以使用像這樣創建一個文件:如何在Android設備的根目錄下創建/寫入文件?

FileOutputStream fs = openFileOutput("/test.in", MODE_WORLD_WRITEABLE); 
String s = "[Head]\r\n"; 
s += "Type=2"; 
byte[] buffer = s.getBytes(); 
fs.write(buffer); 
fs.close(); 

當運行上面的代碼,我得到一個IllegalArgumentException指出:

java.lang.IllegalArgumentException異常: 文件/ test.in包含路徑 分隔符

我在猜測「/」不值得讚賞。我想要的「/」,因爲我需要寫文件到設備的根目錄下,如試圖跟隨在API中指出:

請求是一個文本文件(UNICODE)與 文件擴展名「。在」。所述 應用程序讀取,並且當它被放置在根目錄 在移動設備上解析。在 文件。

問題是:如何將文件放置在根目錄中?我一直在四處尋找答案,但還沒有找到答案。

問候

+0

添加文件看到這http://www.anddev.org/working_with_files-t115.html – Aamirkhan 2012-06-18 07:52:01

+0

作爲第三方應用開​​發者,你不能把根目錄中的文件,期。 – 2014-11-04 23:23:11

回答

7

Context.openFileOutput是指用於創建私人文件到您的應用程序。他們進入你的應用的私人數據目錄。您提供的,而不是一個路徑:「名稱要打開的文件的名稱;不能包含路徑分隔符」。

http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String,INT)

至於你的問題,你不能寫入/除非你是根:

我的Linux的盒子$ ADB殼的ls -l -d/ drwxr -xr-x root root 2010-01-16 07:42 $

我不知道你希望你寫入根目錄的API是什麼,但我猜這不是Android API,你讀錯文檔;-)

+0

感謝您的回答。它是唯一可用於與本應用程序「溝通」的API。通過在上面引用的根目錄中創建文本文件進行通信。所以它不是錯誤的文件 - 它是唯一存在的文件。我會聯繫他們並詢問他們期望在Android上工作=) – Ted 2010-01-17 15:57:47

+2

你確定它不需要你寫入SD卡的根目錄嗎? – 2010-01-18 18:00:45

0

我今天所面臨的同樣的問題

java.lang.IllegalArgumentException異常:文件/test.txt包含路徑分隔符

,當我嘗試了以下它的工作。

  File inputFile = new File("/storage/new/test.txt"); 
      FileInputStream isr = new FileInputStream(inputFile); 
      DataInputStream in = new DataInputStream(isr); 

      if(!inputFile.exists()){ 

        Log.v("FILE","InputFile not available"); 

      } 
      else 
      { 
       while((line = in.readLine()) != null) 
       { 
        ........ //parse 
       } 
      }    

(順便說一句,我得到這個問題外/根目錄和搜索時我看到這個帖子)

+0

Thx爲答案。如果我再次把我的手放到android開發中,我會嘗試一下=) – Ted 2011-04-02 13:38:44

5

您可以用路徑在私有目錄一樣,

String path = this.getApplicationContext().getFilesDir() + "/testDir/"; 
    File file = new File(path); 
    file.mkdirs(); 
    path += "testlab.txt"; 
    OutputStream myOutput; 
    try { 
    myOutput = new BufferedOutputStream(new FileOutputStream(path,true)); 
    write(myOutput, new String("TEST").getBytes()); 
    myOutput.flush(); 
    myOutput.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
+2

「write(OutputStream,Byte [])」在哪裏聲明?我不得不使用myOutput.write(Byte [])來使它工作。 – ArtOfWarfare 2012-08-21 14:10:32

相關問題