Eric Glass
Eric Glass

Reputation: 141

Easy way to switch between InputStream and FileInputStream?

I wrote a large chunk of code with reading text files located on the SD card in mind.
I just realized that I'm going to need to read text files located in the Assets folder as well.
Check out the code I posted below.
If it were possible to do that, my problem would be solved.
Unfortunately, using an IF statement in such a manner is apparently not permitted.

At the moment, my only option is to make a duplicate of all of the file reading code and put it in a separate AsyncTask thread (my file-reading code is currently in an AsyncTask background thread) but it's about 250 lines of code so it would be better if I didn't have to duplicate it.
Any suggestions would be appreciated.

if (switchToAsset == 1);
{
InputStream myStream = getAssets().open(currentFilePath);
}
else
{
FileInputStream myStream = new FileInputStream(currentFilePath);
}
DataInputStream in = new DataInputStream(myStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Upvotes: 0

Views: 227

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198171

 InputStream myStream;
 if (switchToAsset == 1) { // having a semicolon here is BAD BAD BAD
   myStream = getAssets().open(currentFilePath);
 } else {
   myStream = new FileInputStream(currentFilePath);
 }

...or even more concisely...

 InputStream myStream = (switchToAsset == 1)
   ? getAssets().open(currentFilePath)
   : new FileInputStream(currentFilePath)

Upvotes: 1

Related Questions