从资产中读取文件

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"); } } 

我正在使用此代码试图从资产中读取文件。 我尝试了两种方法来做到这一点。 首先在使用File我收到了FileNotFoundException ,使用AssetManager getAssets()方法无法识别。 这里有没有解决办法?

这是我在一个缓冲阅读扩展/修改,以满足您的需求的活动

 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 } } } 

编辑:我的答案也许是无用的,如果你的问题是如何做一个活动之外。 如果你的问题只是如何从资产中读取文件,那么答案就在上面。

更新

要打开指定types的文件,只需在InputStreamReader调用中添加该types,如下所示。

 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在评论中所说,我所给出的代码并没有总结线条。 mLine是每一次更换。 这就是为什么我写了//process line 。 我假设该文件包含某种数据(即联系人列表),每行应分开处理。

如果你只是想不加任何处理地加载文件,你将不得不在每次使用StringBuilder()总结mLine并追加每一个遍。

另一个编辑

根据@Vincent的评论我加了finally块。

另请注意,在Java 7及更高版本中,您可以使用try-with-resources来使用最近Java的AutoCloseableCloseablefunction。

CONTEXT

在@LunarWatcher中指出, getAssets()context一个class 。 因此,如果您将其称为activity之外,则需要引用它并将该上下文实例传递给该活动。

 ContextInstance.getAssets(); 

这在@Maneesh的答案中有解释。 所以,如果这对你有用,你可以提出他的答案,因为那是他指出的。

 getAssets() 

只有在其他任何类的Activity中才能使用Context

为Utils类的构造函数传递活动(丑陋的方式)或应用程序的上下文作为parameter passing给它。 在Utils类中使用getAsset()。

 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(); } 

迟到总比不到好。

在某些情况下,我很难逐行读取文件。 下面的方法是我find的最好的,我推荐它。

用法: 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; } 

编辑 。 明显的问题:这个函数可能会返回这个string:

'android.content.res.AssetManager $ @ AssetInputStream [代码]'

而不是文件内容。 我无法重现这个问题。 直到我更新我的答案,当我得到什么问题时,考虑上面的代码“可能不可靠”。

 AssetManager assetManager = getAssets(); InputStream inputStream = null; try { inputStream = assetManager.open("helloworld.txt"); } catch (IOException e){ Log.e("message: ",e.getMessage()); } 

当您在Activity类中调用时, getAssets()方法将起作用。

如果您在非Activity类中调用此方法,则需要从Activity类中传递的Context中调用此方法。 所以下面是你可以访问的方法。

 ContextInstance.getAssets(); 

ContextInstance可以作为Activity的类传递。

这里是一个读取资产文件的方法:

 /** * 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; } 

如果您使用除“活动”之外的其他任何课程,则可能需要这样做,

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

在MainActivity.java中

 @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))); } } 

另外,你可以创build独立的类来完成所有的工作

 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(); } } 

在我看来,最好是创build一个接口,但不是必需的

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

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 + ""; } 

您可以从文件加载内容。 考虑文件存在于资产文件夹中。

 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; } 

现在您可以通过调用以下函数获取内容

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

考虑data.json存储在Application \ app \ src \ main \ assets \ data.json