2013-11-05 73 views
2

我試圖能夠在資產文件夾中的文件中搜索字符串。 getassets()。open是說它的未定義。 我在某處閱讀這種方式的作品。 這裏是我的代碼:getAssets()在eclipse中顯示錯誤

import java.io.File; 
    import java.util.Scanner; 

    import android.content.Context; 
    import android.util.Log; 

    public class Search { 

public static void LoadStuff(String Name) { 

     Scanner reader = null; 
     try { 
      reader = new Scanner(new File(getAssets().open("myFile.txt"))); 
     } catch (Exception e) { 
     Log.d("damn", "FAIL"); 
     } 
     if(reader != null) 
      Load(reader); 
    } 




private static void Load(Scanner reader) { 
     while (reader.hasNext()) { 
     String result = reader.next(); 
     if (result.equals("water")) { 
      while (result != "KEYEND") { 
       int index = reader.nextInt(); 
       Log.d("Index", String.valueOf(index)); 
      } 
     } 
     } 
      reader.close(); 
    } 
    } 

回答

3

要調用getAssets,但你實際上並沒有上下文從加載。你需要將你的應用程序上下文傳遞給這個類。

public static void LoadStuff(Context appContext, String fileName){ 

然後

appContext.getAssets().open(fileName); 

Scanner構造函數也接受InputStream,所以你的行會變成:

reader = new Scanner(getAssets().open("myFile.txt")); 
+0

它說File(inputStream)是未定義的。 – ChiggyB

+0

您不需要'File','Scanner'構造函數接受'InputStream'。 –

+0

剛剛更新了我的帖子。很高興我能幫忙,祝你好運,快樂編碼! :) –

0

中,爲了使用getAssets(),你需要有BaseApplicationContext或活動上下文方法。

嘗試使用context.getAssets()

AssetManager assets = activityContext.getResources().getAssets(); 
InputStream inputStream = assets.open("SlideImages/"+fullImage); 
+0

現在它說,構造文件(的inputStream)是未定義 – ChiggyB

+0

因爲assests.open是InputStream,所以要儘量理解爲InputStream和轉換(WIRTE)現在到文件 –

2

首先使用Context馬特·克拉克回答..

然後第二件事是getAssets().open("myFile.txt")InputStream沒有File

因此,閱讀它像

InputStream is = context.getAssets().open("myFile.txt"); 
reader = new Scanner(is);