android.content.res.AssetManager Java Examples

The following examples show how to use android.content.res.AssetManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResourceHelper.java    From MaterialDesignSupport with MIT License 6 votes vote down vote up
public static AssetFileDescriptor getAssetFileDescriptor(String assetName) {
    Context context = CoreMaterialApplication.getContext();
    if (context == null) {
        return null;
    }

    AssetManager assets = context.getAssets();
    if (assets == null) {
        return null;
    }

    try {
        return assets.openFd(assetName);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
Example #2
Source File: Helper.java    From VIA-AI with MIT License 6 votes vote down vote up
public static void findAPKFile(String filepath, Context context) {
    String apkFilepath = getAPKFilepath(context);

    // Get the offset and length for the file: theUrl, that is in your
    // assets folder
    AssetManager assetManager = context.getAssets();
    try {

        AssetFileDescriptor assFD = assetManager.openFd(filepath);
        if (assFD != null) {
            long offset = assFD.getStartOffset();
            long fileSize = assFD.getLength();





            assFD.close();

            // **** offset and fileSize are the offset and size
            // **** in bytes of the asset inside the APK
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #3
Source File: Convolution2D.java    From style-transfer with Apache License 2.0 6 votes vote down vote up
public void loadModel(String path) throws IOException {
    mInputStream = mContext.getAssets().open(path + "/W", AssetManager.ACCESS_BUFFER);
    ByteBuffer bb = readInput(mInputStream);
    FloatBuffer.wrap(W).put(bb.asFloatBuffer());

    // padding for GPU BLAS when necessary.
    int W_height_input = in_channels * ksize * ksize;
    if (padded_Y_blas == W_height_input) {
        // If the input width already satisfies the requirement, just copy to the Allocation.
        W_alloc.copyFrom(W);
    } else {
        // If not, a temp allocation needs to be created.
        Allocation input = Allocation.createTyped(mRS,
                Type.createXY(mRS, Element.F32(mRS), W_height_input, out_channels));
        input.copyFrom(W);
        W_alloc.copy2DRangeFrom(0, 0, W_height_input, out_channels, input, 0, 0);
    }

    mInputStream = mContext.getAssets().open(path + "/b", AssetManager.ACCESS_BUFFER);
    bb = readInput(mInputStream);
    FloatBuffer.wrap(b).put(bb.asFloatBuffer());
    b_alloc.copyFrom(b);

    mInputStream.close();
    Log.v(TAG, "Convolution2D loaded: " + b[0]);
}
 
Example #4
Source File: CopyUtil.java    From AndroidWebServ with Apache License 2.0 6 votes vote down vote up
/**
 * @brief assets路径内内容复制进目录路径
 * @param assetsPath assets路径
 * @param dirPath 目录路径
 * @param isSmart true: only when a file doesn't exist; false: override.
 * @throws IOException
 */
public void assetsCopy(String assetsPath, String dirPath, boolean isSmart) throws IOException {
    AssetManager am = mContext.getAssets();
    String[] list = am.list(assetsPath);
    if (list.length == 0) { // 文件
        File file = new File(dirPath);
        if (!isSmart || !file.exists()) {
            file.getParentFile().mkdirs();
            file.createNewFile();
            InputStream in = am.open(assetsPath);
            FileOutputStream fout = new FileOutputStream(file);
            write(in, fout); // 复制
        }
    } else { // 目录
        for (String path : list) {
            assetsCopy(join(assetsPath, path), join(dirPath, path), isSmart);
        }
    }
}
 
Example #5
Source File: PuBuActivity.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pubu_layout);
    puBuLayout = (PuBuLayout) findViewById(R.id.pubu_layout);
    //获取AssetManager
    AssetManager manager = getAssets();
    try {
        //获取Assets目录中的文件,得到文件名数组
        String[] images = manager.list("images");
        for(int i=0; i<images.length;i++){
            //向布局中添加Bitmap
            //把文件转换Bitmap
            InputStream in = manager.open("images/" + images[i]);
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            puBuLayout.addImage(bitmap);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
Example #6
Source File: Utils.java    From Tutorials with Apache License 2.0 6 votes vote down vote up
private static String loadJSONFromAsset(Context context, String jsonFileName) {
    String json = null;
    InputStream is = null;
    try {
        AssetManager manager = context.getAssets();
        Log.d(TAG,"path "+jsonFileName);
        is = manager.open(jsonFileName);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
 
Example #7
Source File: BankUtils.java    From SearchBarView with Apache License 2.0 6 votes vote down vote up
public static ArrayList<Bank> loadHotBank(AssetManager assetManager) {
	ArrayList<Bank> hotBanks = null;
	try {
		InputStream is = assetManager.open("bank/hot_bank.json");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int offset;
		while( (offset = is.read(buffer)) != -1 ) {
			baos.write(buffer, 0, offset);
		}
		is.close();
		baos.flush();
		hotBanks = new Gson().fromJson(baos.toString(), new TypeToken<ArrayList<Bank>>(){}.getType());
		is.close();
		baos.close();
	} catch (IOException e) {
	}
	return hotBanks == null ? new ArrayList<Bank>() : hotBanks;
}
 
Example #8
Source File: DataHelper.java    From Field-Book with GNU General Public License v2.0 6 votes vote down vote up
/**
 * V2 - Helper function to copy multiple files from asset to SDCard
 */
public void copyFileOrDir(String fullPath, String path) {
    AssetManager assetManager = context.getAssets();
    String assets[];

    try {
        assets = assetManager.list(path);

        if (assets.length == 0) {
            copyFile(fullPath, path);
        } else {
            File dir = new File(fullPath);

            if (!dir.exists())
                dir.mkdir();

            for (String asset : assets) {
                copyFileOrDir(fullPath, path + "/" + asset);
            }
        }
    } catch (IOException ex) {
        Log.e("Sample Data", "I/O Exception", ex);
    }
}
 
Example #9
Source File: AndroidProjectManager.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create new android project
 *
 * @param context          - android context to get assets template
 * @param dir              - The directory will contain the project
 * @param projectName      - Name of project, it will be used for create root directory
 * @param useCompatLibrary - <code>true</code> if need copy android compat library
 */
@Override
public AndroidAppProject createNewProject(Context context, File dir, String projectName,
                                          String packageName, String activityName, String mainLayoutName,
                                          String appName, boolean useCompatLibrary) throws Exception {

    String activityClass = String.format("%s.%s", packageName, activityName);
    File projectDir = new File(dir, projectName);
    AndroidAppProject project = new AndroidAppProject(projectDir, activityClass, packageName);
    //create directory
    project.mkdirs();

    AssetManager assets = context.getAssets();
    createGradleFile(project);
    createRes(project, useCompatLibrary, appName);
    createManifest(project, activityClass, packageName, assets);
    createMainActivity(project, activityClass, packageName, activityName, appName, useCompatLibrary, assets);
    createMainLayoutXml(project, mainLayoutName);
    copyLibrary(project, useCompatLibrary);

    return project;
}
 
Example #10
Source File: FontManager.java    From memoir with Apache License 2.0 6 votes vote down vote up
private static void listFontFiles(AssetManager assets, Collection<String> fonts, String path) {
    try {
        String[] list = assets.list(path);
        if (list.length > 0) {
            // it's a folder
            for (String file : list) {
                String prefix = "".equals(path) ? "" : path + File.separator;
                listFontFiles(assets, fonts, prefix + file);
            }
        } else if (path.endsWith("ttf")) {
            // it's a font file
            fonts.add(path);
        }
    } catch (IOException ignore) {
    }
}
 
Example #11
Source File: OC_MainMenu.java    From GLEXP-Team-onebillion with Apache License 2.0 6 votes vote down vote up
public List<String>readingList()
{
    AssetManager am = MainActivity.mainActivity.getAssets();
    String dir = "oc-reading";
    dir = OBUtils.stringByAppendingPathComponent(dir,"books");
    try
    {
        if (OBUtils.assetsDirectoryExists(dir))
        {
            String files[] = am.list(dir);
            return Arrays.asList(files);
        }
    }
    catch (IOException e)
    {

    }
    return Collections.emptyList();
}
 
Example #12
Source File: ReactFontManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
public
@Nullable Typeface getTypeface(
    String fontFamilyName,
    int style,
    AssetManager assetManager) {
  FontFamily fontFamily = mFontCache.get(fontFamilyName);
  if (fontFamily == null) {
    fontFamily = new FontFamily();
    mFontCache.put(fontFamilyName, fontFamily);
  }

  Typeface typeface = fontFamily.getTypeface(style);
  if (typeface == null) {
    typeface = createTypeface(fontFamilyName, style, assetManager);
    if (typeface != null) {
      fontFamily.setTypeface(style, typeface);
    }
  }

  return typeface;
}
 
Example #13
Source File: BitmapTextureAtlasTextureRegionFactory.java    From tilt-game-android with MIT License 6 votes vote down vote up
/**
 * Loads all files from a given assets directory (in alphabetical order) as consecutive tiles of an {@link TiledTextureRegion}.
 *
 * @param pBuildableBitmapTextureAtlas
 * @param pAssetManager
 * @param pAssetSubdirectory to load all files from "gfx/flowers" put "flowers" here (assuming, that you've used {@link BitmapTextureAtlasTextureRegionFactory#setAssetBasePath(String)} with "gfx/" before.)
 * @return
 */
public static TiledTextureRegion createTiledFromAssetDirectory(final BuildableBitmapTextureAtlas pBuildableBitmapTextureAtlas, final AssetManager pAssetManager, final String pAssetSubdirectory) {
	final String[] files;
	try {
		files = pAssetManager.list(BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetSubdirectory);
	} catch (final IOException e) {
		throw new AndEngineRuntimeException("Listing assets subdirectory: '" + BitmapTextureAtlasTextureRegionFactory.sAssetBasePath + pAssetSubdirectory + "' failed. Does it exist?", e);
	}
	final int fileCount = files.length;
	final TextureRegion[] textures = new TextureRegion[fileCount];

	for (int i = 0; i < fileCount; i++) {
		final String assetPath = pAssetSubdirectory + "/" + files[i];
		textures[i] = BitmapTextureAtlasTextureRegionFactory.createFromAsset(pBuildableBitmapTextureAtlas, pAssetManager, assetPath);
	}

	return new TiledTextureRegion(pBuildableBitmapTextureAtlas, textures);
}
 
Example #14
Source File: EmoManager.java    From Android with MIT License 6 votes vote down vote up
private void initEMJCategories() {
    AssetManager assetManager = BaseApplication.getInstance().getBaseContext().getResources().getAssets();
    try {
        String[] files = assetManager.list(EMOJI_PATH);
        StickerCategory category;
        for (String name : files) {
            if (!FileUtil.hasExtentsion(name)) {
                if (null == stickerOrder.get(name)) continue;
                int posi = stickerOrder.get(name);
                boolean bigStick = bigStickers.contains(name);
                category = new StickerCategory(name, posi, bigStick);
                stickerCategories.add(category);
            }
        }

        Collections.sort(stickerCategories, new Comparator<StickerCategory>() {
            @Override
            public int compare(StickerCategory lhs, StickerCategory rhs) {
                return lhs.getOrder() - rhs.getOrder();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: SplashActivity.java    From IslamicLibraryAndroid with GNU General Public License v3.0 6 votes vote down vote up
@NonNull
@Override
protected Boolean doInBackground(Void... voids) {
    SplashActivity activity = activityReference.get();
    StorageUtils.makeIslamicLibraryShamelaDirectory(activity);
    if (activity != null) {
        AssetManager assetManager = activity.getAssets();
        InputStream in;
        try {
            in = assetManager.open(DownloadFileConstants.COMPRESSED_ONLINE_DATABASE_NAME);
            if (!UnZipIntentService.unzip(in,
                    StorageUtils.getIslamicLibraryShamelaBooksDir(activity),
                    this::publishProgress)) {
                throw new IOException("unzip failed for main database");
            }
        } catch (IOException e) {
            Timber.e(e);
            return false;
        }
    }
    return true;
}
 
Example #16
Source File: GhostActivity.java    From jterm-cswithandroid with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ghost);
    AssetManager assetManager = getAssets();
    try {
        InputStream inputStream = assetManager.open("words.txt");
        //dictionary = new SimpleDictionary(inputStream);
        dictionary = new FastDictionary(inputStream);
    } catch (IOException e) {
        Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
        toast.show();
    }
    if (savedInstanceState == null) {
        onStart(null);
    } else {
        userTurn = savedInstanceState.getBoolean(KEY_USER_TURN);
        currentWord = savedInstanceState.getString(KEY_CURRENT_WORD);
        String status = savedInstanceState.getString(KEY_SAVED_STATUS);
        ((TextView) findViewById(R.id.ghostText)).setText(currentWord);
        ((TextView) findViewById(R.id.gameStatus)).setText(status);
    }
}
 
Example #17
Source File: Utils.java    From Tutorials with Apache License 2.0 6 votes vote down vote up
private static String loadJSONFromAsset(Context context, String jsonFileName) {
    String json = null;
    InputStream is = null;
    try {
        AssetManager manager = context.getAssets();
        Log.d(TAG, "path " + jsonFileName);
        is = manager.open(jsonFileName);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
 
Example #18
Source File: ProtifyApplication.java    From sbt-android-protify with Apache License 2.0 6 votes vote down vote up
static void install(String externalResourceFile) {
    try {
        AssetManager newAssetManager = createAssetManager(externalResourceFile);

        // Find the singleton instance of ResourcesManager
        Class<?> clazz = Class.forName("android.app.ActivityThread");
        Method mGetInstance = clazz.getDeclaredMethod("currentActivityThread");
        mGetInstance.setAccessible(true);
        Object resourcesManager = mGetInstance.invoke(null);

        // Iterate over all known Resources objects
        Field fMActiveResources = clazz.getDeclaredField("mActiveResources");
        fMActiveResources.setAccessible(true);
        @SuppressWarnings("unchecked")
        Map<?, WeakReference<Resources>> arrayMap =
                (Map<?, WeakReference<Resources>>) fMActiveResources.get(resourcesManager);
        setAssetManager(arrayMap, newAssetManager);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example #19
Source File: BitmapFont.java    From tilt-game-android with MIT License 6 votes vote down vote up
public BitmapFontPage(final AssetManager pAssetManager, final String pAssetBasePath, final String pData) throws IOException {
	final String[] pageAttributes = TextUtils.SPLITPATTERN_SPACE.split(pData, BitmapFont.TAG_PAGE_ATTRIBUTECOUNT + 1);

	if ((pageAttributes.length - 1) != BitmapFont.TAG_PAGE_ATTRIBUTECOUNT) {
		throw new FontException("Expected: '" + BitmapFont.TAG_PAGE_ATTRIBUTECOUNT + "' " + BitmapFont.TAG_PAGE + " attributes, found: '" + (pageAttributes.length - 1) + "'.");
	}
	if (!pageAttributes[0].equals(BitmapFont.TAG_PAGE)) {
		throw new FontException("Expected: '" + BitmapFont.TAG_PAGE + "' attributes.");
	}

	this.mID = BitmapFont.getIntAttribute(pageAttributes, BitmapFont.TAG_PAGE_ATTRIBUTE_ID_INDEX, BitmapFont.TAG_PAGE_ATTRIBUTE_ID);
	final String file = BitmapFont.getStringAttribute(pageAttributes, BitmapFont.TAG_PAGE_ATTRIBUTE_FILE_INDEX, BitmapFont.TAG_PAGE_ATTRIBUTE_FILE);

	final String assetPath = pAssetBasePath + file;
	this.mTexture = new BitmapTexture(BitmapFont.this.mTextureManager, new AssetInputStreamOpener(pAssetManager, assetPath), BitmapFont.this.mBitmapTextureFormat, BitmapFont.this.mTextureOptions);
}
 
Example #20
Source File: HttpStaticProcessor.java    From AndroidGodEye with Apache License 2.0 5 votes vote down vote up
private static String loadContent(String fileName, AssetManager assetManager) throws IOException {
    InputStream input = null;
    try {
        input = assetManager.open(fileName);
        return IoUtil.inputStreamToString(input);
    } finally {
        IoUtil.closeSilently(input);
    }
}
 
Example #21
Source File: EmptyLayout.java    From CoreModule with Apache License 2.0 5 votes vote down vote up
public void setErrorType(int i) {
    setVisibility(View.VISIBLE);
    switch (i) {
        case NETWORK_ERROR:
            mErrorState = NETWORK_ERROR;
            tv.setText(R.string.emptyview_load_again);
            img.setImageResource(R.mipmap.emptyview_icon_network);
            setVisibility(View.VISIBLE);
            clickEnable = true;
            break;
        case NETWORK_LOADING:
            mErrorState = NETWORK_LOADING;
            try {
                AssetManager assetManager = getResources().getAssets();
                String[] loadingList = assetManager.list(LOADING_IMAGE_FOLDER_NAME);
                String imageName = loadingList[((int) (loadingList.length * Math.random()))];
                String absoluteImageName = LOADING_IMAGE_FOLDER_NAME + File.separator + imageName;
                loadingDrawable = new GifDrawable(assetManager, absoluteImageName);
                img.setImageDrawable(loadingDrawable);
            } catch (Exception e) {
            }
            tv.setText(R.string.emptyview_loading);
            clickEnable = false;
            setVisibility(View.VISIBLE);
            break;
        case NODATA:
            mErrorState = NODATA;
            img.setImageResource(R.mipmap.emptyview_icon_empty);
            setTvNoDataContent();
            clickEnable = true;
            setVisibility(View.VISIBLE);
            break;
        case HIDE_LAYOUT:
            dismiss();
            break;
        default:
            break;
    }
}
 
Example #22
Source File: Injecter.java    From cordova-plugin-fastrde-injectview with MIT License 5 votes vote down vote up
public void injectJavascriptFile(String scriptFile){
     	Context context=this.cordova.getActivity().getApplicationContext();
     	AssetManager assetManager = context.getAssets();
      InputStream input;
      try {
        input = context.getAssets().open(scriptFile+".js");
        byte[] buffer = new byte[input.available()];
        input.read(buffer);
        input.close();

           // String-ify the script byte-array using BASE64 encoding !!!
           String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
           this.webView.loadUrl("javascript:(function() {" +
                   "if (document.getElementById('file_"+scriptFile+"') == null) {" +
                        "var parent = document.getElementsByTagName('head').item(0);" +
                        "var script = document.createElement('script');" +
                        "script.id = 'file_"+scriptFile+"';" +
                        "script.type = 'text/javascript';" +
           // Tell the browser to BASE64-decode the string into your script !!!
                        "script.innerHTML = window.atob('" + encoded + "');" +
                        "parent.appendChild(script);" +
                   "}" +
                        "})()");
        } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }

}
 
Example #23
Source File: FileUtils.java    From SprintNBA with Apache License 2.0 5 votes vote down vote up
/**
 * 打开Asset下的文件
 *
 * @param context
 * @param fileName
 * @return
 */
public static InputStream openAssetFile(Context context, String fileName) {
    AssetManager am = context.getAssets();
    InputStream is = null;
    try {
        is = am.open(fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return is;
}
 
Example #24
Source File: AssetUtil.java    From pandora with Apache License 2.0 5 votes vote down vote up
private static void copyFileOrDir(Context context, String path) {
    AssetManager assetManager = context.getAssets();
    String assets[];
    try {
        Log.i("tag", "copyFileOrDir() " + path);
        assets = assetManager.list(path);
        if (assets.length == 0) {
            copyFile(context, path);
        } else {
            String fullPath = TARGET_BASE_PATH + path;
            Log.i("tag", "path=" + fullPath);
            File dir = new File(fullPath);
            if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                if (!dir.mkdirs())
                    Log.i("tag", "could not create dir " + fullPath);
            for (int i = 0; i < assets.length; ++i) {
                String p;
                if (path.equals(""))
                    p = "";
                else
                    p = path + "/";

                if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
                    copyFileOrDir(context, p + assets[i]);
            }
        }
    } catch (IOException ex) {
        Log.e("tag", "I/O Exception", ex);
    }
}
 
Example #25
Source File: TensorFlowHelper.java    From androidthings-imageclassifier with Apache License 2.0 5 votes vote down vote up
public static List<String> readLabels(Context context, String labelsFile) {
    AssetManager assetManager = context.getAssets();
    ArrayList<String> result = new ArrayList<>();
    try (InputStream is = assetManager.open(labelsFile);
         BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        String line;
        while ((line = br.readLine()) != null) {
            result.add(line);
        }
        return result;
    } catch (IOException ex) {
        throw new IllegalStateException("Cannot read labels from " + labelsFile);
    }
}
 
Example #26
Source File: BaseAndroidServerConfigFactory.java    From android-http-server with GNU General Public License v3.0 5 votes vote down vote up
private ResourceProvider getAssetsResourceProvider(final MimeTypeMapping mimeTypeMapping) {
    String assetBasePath = "public";
    if (context != null) {
        AssetManager assetManager = ((Context) context).getResources().getAssets();
        return new AssetResourceProvider(assetManager, assetBasePath);
    } else {
        return new FileSystemResourceProvider(new RangeParser(), new RangeHelper(),
                new RangePartHeaderSerializer(), mimeTypeMapping, "./app/src/main/assets/" + assetBasePath);
    }
}
 
Example #27
Source File: FixedPredictionTest.java    From pasm-yolov3-Android with GNU General Public License v3.0 5 votes vote down vote up
private Bitmap loadFirstImage() throws IOException {
    checkPermissions();
    Context testContext = InstrumentationRegistry.getInstrumentation().getContext();
    AssetManager assetManager = testContext.getAssets();

    String pathToImages = "images";
    String[] list = assetManager.list(pathToImages);
    return getBitmapFromTestAssets(list[0], pathToImages);
}
 
Example #28
Source File: Fonts.java    From AndroidCommons with Apache License 2.0 5 votes vote down vote up
private static void applyAllRecursively(ViewGroup viewGroup, AssetManager assets) {
    for (int i = 0, size = viewGroup.getChildCount(); i < size; i++) {
        final View childView = viewGroup.getChildAt(i);
        if (childView instanceof TextView) {
            setTypeface((TextView) childView, assets, false);
        } else if (childView instanceof ViewGroup) {
            applyAllRecursively((ViewGroup) childView, assets);
        }
    }
}
 
Example #29
Source File: AssertLoader.java    From iBeebo with GNU General Public License v3.0 5 votes vote down vote up
protected String ReadFile(Context context, String fileName)
        throws IOException {
    final AssetManager am = context.getAssets();
    final InputStream inputStream = am.open(fileName);

    scanner = new Scanner(inputStream, "UTF-8");
    return scanner.useDelimiter("\\A").next();
}
 
Example #30
Source File: ExampleInstrumentedTest.java    From XmlToJson with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInputStreamTest() throws Exception {
    Context context = InstrumentationRegistry.getTargetContext();
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open("common.xml");
    inputStream.close(); // CLOSE INPUT STREAM
    XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null).build();
    String json = xmlToJson.toString();
    assertEquals("{}", json);
}