2012-12-21 24 views
7

我的代碼正道文件是繼::如何獲得Android中

Scanner sc = null; 
try { 
    sc = new Scanner(new File("assets/mainmenu/readSourceFile.txt")); 
} catch (FileNotFoundException e1) { 
    // TODO Auto-generated catch block 
    System.out.println(e1.toString()); 
    e1.printStackTrace(); 
} 

然後,logcat的顯示異常java.io.FileNotFoundException

怎樣才能找到我的文件?我試圖

sc = new Scanner(new File("mainmenu/readSourceFile.txt"));

但是,它仍然拋出FilenotFoundException

我的文件夾中的資產/ MainMenu的/ readSourceFile.txt

,我已經嘗試這種::

private InputStream is; 
try { 
     is = this.getResources().getAssets().open("mainmenu/readSourceFile.txt"); 
    } catch (IOException e) { 
     e.toString(); 
    } 

我使用getAssets來訪問Android中的資產文件。但是,我怎麼能想,如果我用InputStream

+0

是你所有的目錄都位於同一個項目?如果是這樣,只需將路徑設爲./assets/mainmenu/readSourceFile.txt .. – gks

+0

@barssala你的文本文件在資產文件夾中? – vnshetty

+0

當然,我的文本文件在資產/ mainmenu/readSourceFile.txt – barssala

回答

1

你試試這個...希望閱讀的文本文件,它會工作

sc = new Scanner(new File("file:///android_asset/mainmenu/readSourceFile.txt"); 

編輯試試這個

AssetFileDescriptor descriptor = getAssets().openFd("mainmenu/readSourceFile.txt"); 
FileReader reader = new FileReader(descriptor.getFileDescriptor()); 

從這裏Asset folder path

複製
+0

對不起,但我得到了'FileNotFoundException' – barssala

+0

@barssala參見編輯 – vnshetty

+0

瞭解更多信息。 java.io.FileNotFoundException:/ file:/android_asset/mainmenu/readSourceFile.txt – barssala

0

您無法訪問Android應用程序的assets文件夾,就好像它們是文件系統上的常規文件(提示:它們不是)。相反,您需要在您的活動/應用上下文中使用AssetManager .Call getAssets()以獲得AssetManager

一旦你有了這個,你可以使用open("mainmenu/readSourceFile.txt")獲得InputStream

您現在可以像讀取其他任何內容一樣閱讀此InputStreamApache Commons IO是用於處理輸入和輸出流的優秀庫。這取決於你如何想要得到的數據,你可以嘗試:

  • 閱讀整個文件轉換成字符串:

    try { 
        String contents = IOUtils.toString(in); 
    } finally { 
        IOUtils.closeQuietly(in); 
    } 
    
  • 將整個文件讀入一個字符串列表,每行一個:

    try { 
        List<String> lines = IOUtils.readLines(in); 
    } finally { 
        IOUtils.closeQuietly(in); 
    } 
    
  • 迭代通過在一個時間文件的一行:

    try { 
        LineIterator it = IOUtils.lineIterator(in, "UTF-8"); 
        while (it.hasNext()) { 
         String line = it.nextLine(); 
         // do something with line 
        } 
    } finally { 
        IOUtils.closeQuietly(in); 
    } 
    
+0

我試過'InputStream',現在我可以打開文件。但是我不知道如何使用'InputStream'' – barssala

+0

[Apache Commons IO](http://commons.apache.org/io/description.html)使得這很簡單,如何閱讀文本文件。下載'commons-io-2.4.jar'並將其添加到Java構建路徑中,然後您可以一次讀取該文件:'String mContents = IOUtils.toString(mInputStream)'。如果你不想使用'IOUtils'出於某種原因,這個鏈接還顯示瞭如何手動執行同樣的操作('InputStream' - >'InputStreamReader' - >'BufferedReader' - > loop)... – user113215

0

我有同樣的問題。我注意到文件不應該包含層次結構。如果將來有人遇到同樣的問題,這對我很有幫助。 `

InputStream is=null; 

    try { 
     is=activity.getAssets().open("fileInAssets.dat"); 
    } catch (IOException e1) { 
     Log.e(TAG, "Erro while openning hosts file."); 
     e1.printStackTrace(); 
    } 

`