I have a fileReader that works in Java but the same method doesn't work for Android Studios. The code I use in Eclipse to read my text file data is:
public void addTextFilesToCardsArrayList(String fileName) throws IOException{
FileReader freader = new FileReader(fileName);
BufferedReader reader = new BufferedReader(freader);
String line = null;
try {
while ((line = reader.readLine()) != null) { //Read a file line by line
String[] split = line.split(","); //Parse the line in to usable fragments
int cardNumber = Integer.parseInt(split[0]);
String cardId = split[1];
int apc = Integer.parseInt(split[2]);
int hp = Integer.parseInt(split[3]);
String type = split[4];
Card card = new Card(cardNumber, cardId, apc, hp, type);
cards.add(card);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
I placed a text file called "cards.txt" in the asset folder that I created in "main" directory. Normally I pass it in as a paramter like "cards.txt" in Eclipse. How do I get it working in Android Studios fileReader?
I've seen InputStream is = getAssets().open("file.txt"); being used but I've liked to keep my method mostly the same without rewriting my fileReader code.
I placed a text file called "cards.txt" in the asset folder that I created in "main" directory
That is a file on your development machine. It is not a file on your Android device.
I've seen InputStream is = getAssets().open("file.txt"); being used
That is the correct approach to use.
but I've liked to keep my method mostly the same without rewriting my fileReader code.
Then pass in an InputStream
rather than a String
to addTextFilesToCardsArrayList()
. Replace FileReader
with InputStreamReader
. In Android, use the InputStream
from getAssets().open()
. Elsewhere, use a FileInputStream
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.