简体   繁体   English

如何在Android Studio中使用fileReader读取文本文件数据?

[英]How can I use fileReader to read text file data in Android Studios?

I have a fileReader that works in Java but the same method doesn't work for Android Studios. 我有一个可以在Java中使用的fileReader,但相同的方法不适用于Android Studio。 The code I use in Eclipse to read my text file data is: 我在Eclipse中用来读取文本文件数据的代码是:

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. 我在“主”目录中创建的资产文件夹中放置了一个名为“ cards.txt”的文本文件。 Normally I pass it in as a paramter like "cards.txt" in Eclipse. 通常,我将其作为参数传递给Eclipse中的“ cards.txt”。 How do I get it working in Android Studios fileReader? 如何在Android Studios fileReader中使用它?

I've seen InputStream is = getAssets().open("file.txt"); 我已经看到InputStream是= getAssets()。open(“ file.txt”); being used but I've liked to keep my method mostly the same without rewriting my fileReader code. 被使用,但我一直希望在不重写fileReader代码的情况下保持方法基本相同。

I placed a text file called "cards.txt" in the asset folder that I created in "main" directory 我在“主要”目录中创建的资产文件夹中放置了一个名为“ cards.txt”的文本文件

That is a file on your development machine. 那是开发机器上的文件。 It is not a file on your Android device. 它不是Android设备上的文件。

I've seen InputStream is = getAssets().open("file.txt"); 我已经看到InputStream是= 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. 但我一直希望在不重写fileReader代码的情况下保持方法基本相同。

Then pass in an InputStream rather than a String to addTextFilesToCardsArrayList() . 然后将InputStream而不是String传递给addTextFilesToCardsArrayList() Replace FileReader with InputStreamReader . InputStreamReader替换FileReader In Android, use the InputStream from getAssets().open() . 在Android中,使用getAssets().open()InputStream Elsewhere, use a FileInputStream . 在其他地方,使用FileInputStream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM