The Android FileIO Class

The original FileIO interface was lean and mean. It only contained three methods: one to get an InputStream for an asset, another to get an InputStream for a file on the external storage, and a third that returns an OutputStream for a file on the external storage. In Chapter 4 you learned how we can open assets and files on the external storage with the Android APIs. Listing 5-1 shows you the implementation of the FileIO interface we'll use based on the knowledge from Chapter 4.

Listing 5-1. AndroidFileIO.java; Implementing the FileIO Interface package com.badlogic.androidgames.framework.impl;

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;

import android.content.res.AssetManager; import android.os.Environment;

import com.badlogic.androidgames.framework.FileIO;

public class AndroidFileIO implements FileIO { AssetManager assets; String externalStoragePath;

public AndroidFileIO(AssetManager assets) { this.assets = assets;

this.externalStoragePath = Environment.getExternalStorageDirectory() .getAbsolutePath() + File.separator;

@Override public InputStream readAsset(String fileName) throws IOException { return assets.open(fileName);

@Override public InputStream readFile(String fileName) throws IOException { return new FileInputStream(externalStoragePath + fileName);

@Override public OutputStream writeFile(String fileName) throws IOException { return new FileOutputStream(externalStoragePath + fileName);

Everything's straightforward. We implement the FileIO interface, store an AssetManager along with the path of the external storage, and implement the three methods based on this. We pass through any IOExceptions that get thrown so we'll know if anything is fishy on the calling side.

Our Game interface implementation will hold an instance of this class and return it via Game.getFileIO(). This also means that our Game implementation will need to pass in the AssetManager later on for the AndroidFileIO instance to work.

Note that we do not check for the external storage to be available. If it's not available, or if we forgot to add the proper permission to the manifest file, we'll get an exception, so error checking is done implicitly. So we can move on to the next pieces of our framework: audio.

0 0

Post a comment