2012-03-03 21 views
120
public class Utils { 
    public static List<Message> getMessages() { 
     //File file = new File("file:///android_asset/helloworld.txt"); 
     AssetManager assetManager = getAssets(); 
     InputStream ims = assetManager.open("helloworld.txt");  
    } 
} 

私はこのコードを使用してアセットからファイルを読み取っています。私はこれを行うには2つの方法を試しました。まず、Fileを使用した場合FileNotFoundExceptionを受け取ったとき、AssetManager getAssets()メソッドを使用していると認識されません。 ここに解決策はありますか?アセットからファイルを読み取る

答えて

174

は、私は、バッファ読書のための活動に何をすべきかです/拡張ニーズ

に一致するように変更
BufferedReader reader = null; 
try { 
    reader = new BufferedReader(
     new InputStreamReader(getAssets().open("filename.txt"))); 

    // do reading, usually loop until end of file reading 
    String mLine; 
    while ((mLine = reader.readLine()) != null) { 
     //process line 
     ... 
    } 
} catch (IOException e) { 
    //log the exception 
} finally { 
    if (reader != null) { 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      //log the exception 
     } 
    } 
} 

EDIT:あなたの質問は、活動の外でそれを行う方法である場合私の答えは、おそらく無用です。あなたの質問が単純に資産からファイルを読み込む方法であれば、答えは上記のとおりです。

UPDATE

単に以下のようにInputStreamReader呼び出しでタイプを追加するタイプを指定してファイルを開くには。

BufferedReader reader = null; 
try { 
    reader = new BufferedReader(
     new InputStreamReader(getAssets().open("filename.txt"), "UTF-8")); 

    // do reading, usually loop until end of file reading 
    String mLine; 
    while ((mLine = reader.readLine()) != null) { 
     //process line 
     ... 
    } 
} catch (IOException e) { 
    //log the exception 
} finally { 
    if (reader != null) { 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      //log the exception 
     } 
    } 
} 

@Stanコメントで言うようにEDIT

は、私が与えているコードは、行を合計されていません。パスごとにmLineが置き換えられます。だから私は//process lineと書いた。ファイルに何らかの種類のデータ(連絡先リスト)が含まれていて、各行を別々に処理する必要があるとします。

何らかの処理を行わずにファイルをロードしたい場合は、StringBuilder()を使用してパスごとにmLineを合計し、各パスを追加する必要があります。 @Vincentのコメントによると

ANOTHER EDIT私はfinallyブロックを追加しました。

Java 7以上では、AutoCloseableと最近のJavaの機能を使用するのにtry-with-resourcesを使用できます。 getAssets()contextclassであることを指摘し@LunarWatcherコメントで

CONTEXT

。だから、activityの外に呼び出すと、それを参照してコンテキストインスタンスをアクティビティに渡す必要があります。

ContextInstance.getAssets(); 

これは@Maneeshの答えで説明されています。だから、もしあなたが彼の答えをアップアップすることが役に立つなら、それは彼がそれを指摘した人だからです。

+0

このコードは、毎回 – Stan

+2

@Stanを渡すたびにmLineの内容を置き換えることに失敗します。それからコメントに書き込んで、作者に更新を希望するかどうかを決定させてください。編集は、意味を変えずに明瞭さを向上させるためのものです。コードの改訂は常にコメントとして投稿する必要があります。 – KyleMit

+0

ええ、私は、高すぎるそれを得た! EDITの機能について言及していただきありがとうございます。私はすぐにこのコメントを削除するつもりはないなどもあなたのコメントを上に投票した – Stan

60
getAssets() 

があるだけで、あなたはそれのためにContextを使用する必要があり、他の任意のクラスでの活動で動作します。

Utilsのアクティビティ(醜いやり方)のクラスパス参照またはアプリケーションのコンテキストをパラメータとしてのコンストラクタを作成します。これを使用すると、UtilsクラスでgetAsset()を使用します。ここで

+0

これはCoのサブクラスntextのうち、アクティビティは多くのうちの1つです。 –

+0

ちょうど私は 'Context'を書きました。 – user370305

+0

@ user370305あなたはInputStreamをFileInputStreamにどのように変換できますか? –

6

getAssets()メソッドは、アクティビティクラス内で呼び出すときに機能します。

Activity以外のクラスでこのメソッドを呼び出すと、Activityクラスから渡されたContextからこのメソッドを呼び出す必要があります。以下は、メソッドにアクセスできる行です。

ContextInstance.getAssets(); 

ContextInstanceがこのアクティビティクラスとして渡されます。

9
AssetManager assetManager = getAssets(); 
InputStream inputStream = null; 
try { 
    inputStream = assetManager.open("helloworld.txt"); 
} 
catch (IOException e){ 
    Log.e("message: ",e.getMessage()); 
} 
32
public String ReadFromfile(String fileName, Context context) { 
    StringBuilder returnString = new StringBuilder(); 
    InputStream fIn = null; 
    InputStreamReader isr = null; 
    BufferedReader input = null; 
    try { 
     fIn = context.getResources().getAssets() 
       .open(fileName, Context.MODE_WORLD_READABLE); 
     isr = new InputStreamReader(fIn); 
     input = new BufferedReader(isr); 
     String line = ""; 
     while ((line = input.readLine()) != null) { 
      returnString.append(line); 
     } 
    } catch (Exception e) { 
     e.getMessage(); 
    } finally { 
     try { 
      if (isr != null) 
       isr.close(); 
      if (fIn != null) 
       fIn.close(); 
      if (input != null) 
       input.close(); 
     } catch (Exception e2) { 
      e2.getMessage(); 
     } 
    } 
    return returnString.toString(); 
} 
+0

BufferedReaderを閉じると、InputStreanReaderとInputStreamも自動的に閉じる必要があると考えられます。それはあなたがそれらのハンドルを作成しないためです。 'input = new BufferedReader(新しいInputStreamReader(fIn));'。 – trans

+1

最後にすべてのリソースを閉じるためのtry/catchブロックを別々に作成することをお勧めします。以前の別のリソースを閉じる試みで例外がスローされた場合、他のリソースをクローズしないままにする可能性があるため、すべてを1つにまとめるのではなく、 – Reece

30

ないより遅れて。

状況によってはファイルを1行ずつ読み込むのが困難でした。 下記の方法が私が見つけた最高のものです。これまでのところ、私はそれをお勧めします。

使用:String yourData = LoadData("YourDataFile.txt");

YourDataFile.txt資産/

public String LoadData(String inFile) { 
     String tContents = ""; 

    try { 
     InputStream stream = getAssets().open(inFile); 

     int size = stream.available(); 
     byte[] buffer = new byte[size]; 
     stream.read(buffer); 
     stream.close(); 
     tContents = new String(buffer); 
    } catch (IOException e) { 
     // Handle exceptions here 
    } 

    return tContents; 

} 

EDITに常駐することが想定されます。見かけの問題:この関数は、この文字列を返すことがあります:

'android.content.res.AssetManager $ AssetInputStream @ [コード]' ではなく、ファイルの内容の

。私はまだ問題を再現することができません。問題が何であるかを知るときに私の答えを更新するまで、上記のコードは「おそらく信頼できない」と考えてください。 、あなたが活動以外の任意のクラスを使用する場合は、あなたが好きですしたい場合があります

/** 
* Reads the text of an asset. Should not be run on the UI thread. 
* 
* @param mgr 
*   The {@link AssetManager} obtained via {@link Context#getAssets()} 
* @param path 
*   The path to the asset. 
* @return The plain text of the asset 
*/ 
public static String readAsset(AssetManager mgr, String path) { 
    String contents = ""; 
    InputStream is = null; 
    BufferedReader reader = null; 
    try { 
     is = mgr.open(path); 
     reader = new BufferedReader(new InputStreamReader(is)); 
     contents = reader.readLine(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      contents += '\n' + line; 
     } 
    } catch (final Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (is != null) { 
      try { 
       is.close(); 
      } catch (IOException ignored) { 
      } 
     } 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException ignored) { 
      } 
     } 
    } 
    return contents; 
} 
+0

戻り値の文字列は[email protected]です。 –

+0

res.AssetManager $ AssetInputStream @ ....これを返す理由は何ですか? – Bigs

+1

は私にとってはうまく動作します – Fabian

4

は、資産のファイルを読むための方法であり、

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     TextView tvView = (TextView) findViewById(R.id.tvView); 

     AssetsReader assetsReader = new AssetsReader(this); 
     if(assetsReader.getTxtFile(your_file_title)) != null) 
     { 
      tvView.setText(assetsReader.getTxtFile(your_file_title))); 
     } 
    } 

また、すべての作業を行う別のクラスを作成することもできます

public class AssetsReader implements Readable{ 

    private static final String TAG = "AssetsReader"; 


    private AssetManager mAssetManager; 
    private Activity mActivity; 

    public AssetsReader(Activity activity) { 
     this.mActivity = activity; 
     mAssetManager = mActivity.getAssets(); 
    } 

    @Override 
    public String getTxtFile(String fileName) 
    { 
     BufferedReader reader = null; 
     InputStream inputStream = null; 
     StringBuilder builder = new StringBuilder(); 

     try{ 
      inputStream = mAssetManager.open(fileName); 
      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 

      while((line = reader.readLine()) != null) 
      { 
       Log.i(TAG, line); 
       builder.append(line); 
       builder.append("\n"); 
      } 
     } catch (IOException ioe){ 
      ioe.printStackTrace(); 
     } finally { 

      if(inputStream != null) 
      { 
       try { 
        inputStream.close(); 
       } catch (IOException ioe){ 
        ioe.printStackTrace(); 
       } 
      } 

      if(reader != null) 
      { 
       try { 
        reader.close(); 
       } catch (IOException ioe) 
       { 
        ioe.printStackTrace(); 
       } 
      } 
     } 
     Log.i(TAG, "builder.toString(): " + builder.toString()); 
     return builder.toString(); 
    } 
} 

私の意見では、インターフェイスを作成すると良いでしょうが、それはあなたがファイルからコンテンツをロードすることができます

public interface Readable { 
    /** 
    * Reads txt file from assets 
    * @param fileName 
    * @return string 
    */ 
    String getTxtFile(String fileName); 
} 
2

MainActivity.javaで

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(YourApplication.getInstance().getAssets().open("text.txt"), "UTF-8")); 
2

:ここ

0

cityfile.txt

public void getCityStateFromLocal() { 
     AssetManager am = getAssets(); 
     InputStream inputStream = null; 
     try { 
      inputStream = am.open("city_state.txt"); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     ObjectMapper mapper = new ObjectMapper(); 
     Map<String, String[]> map = new HashMap<String, String[]>(); 
     try { 
      map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() { 
      }); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     ConstantValues.arrayListStateName.clear(); 
     ConstantValues.arrayListCityByState.clear(); 
     if (map.size() > 0) 
     { 
      for (Map.Entry<String, String[]> e : map.entrySet()) { 
       CityByState cityByState = new CityByState(); 
       String key = e.getKey(); 
       String[] value = e.getValue(); 
       ArrayList<String> s = new ArrayList<String>(Arrays.asList(value)); 
       ConstantValues.arrayListStateName.add(key); 
       s.add(0,"Select City"); 
       cityByState.addValue(s); 
       ConstantValues.arrayListCityByState.add(cityByState); 
      } 
     } 
     ConstantValues.arrayListStateName.add(0,"Select States"); 
    } 
// Convert InputStream to String 
    public String getStringFromInputStream(InputStream is) { 
     BufferedReader br = null; 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     try { 
      br = new BufferedReader(new InputStreamReader(is)); 
      while ((line = br.readLine()) != null) { 
       sb.append(line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (br != null) { 
       try { 
        br.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

     return sb + ""; 

    } 
0

必要ありませんです。ファイルがアセットフォルダにあるとします。data.jsonを考慮

String json= FileUtil.loadContentFromFile(context, "data.json"); 

アプリケーションで保存されて従うよう

public static InputStream loadInputStreamFromAssetFile(Context context, String fileName){ 
    AssetManager am = context.getAssets(); 
    try { 
     InputStream is = am.open(fileName); 
     return is; 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

public static String loadContentFromFile(Context context, String path){ 
    String content = null; 
    try { 
     InputStream is = loadInputStreamFromAssetFile(context, path); 
     int size = is.available(); 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     content = new String(buffer, "UTF-8"); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
     return null; 
    } 
    return content; 
} 

は今、あなたは、関数を呼び出してコンテンツを取得することができます\アプリ\ SRC \メイン\資産\ data.json

0

Kotlinを使用すると、Androidのアセットからファイルを読み込むために次の操作を行うことができます:

try { 
     val inputStream:InputStream = assets.open("helloworld.txt") 
     val inputString = inputStream.bufferedReader().use{it.readText()} 
     Log.d(TAG,inputString) 
    } catch (e:Exception){ 
     Log.d(TAG, e.toString()) 
    } 
関連する問題