简体   繁体   English

从Android的文件加载数组

[英]Loading array from file for android

File sample = new File("words.txt");

Scanner readWords = new Scanner(words);

while(scanner.hasNextLine())
{
    //assume that arrayListOfWords is a previously declared arrayList
    arrayListOfWords.add(readWords.nextLine());
}

Will the above code correctly load all the words from a .txt file into an arraylist, assuming that each word is on a separate line, with no blank lines? 假设每个单词在单独的行上且没有空行,上述代码是否可以将.txt文件中的所有单词正确加载到arraylist中?

I'm developing an android app, so in which of my project folders am I supposed to put the actual file? 我正在开发一个android应用,因此我应该在哪个项目文件夹中放置实际文件?

When can I put just "words.txt" and when do I have to type the full path name, like C:\\Users\\etc... 什么时候可以只输入“ words.txt”,什么时候必须键入完整的路径名,例如C:\\ Users \\ etc ...

Also, once the program compiles and is turned into an .apk file, how will it still load the words from the .txt file if the file is located on my computer? 此外,一旦程序编译并转换为.apk文件,如果该文件位于我的计算机上,它将如何仍然从.txt文件加载单词? If someone else uses the app, wouldn't the app not be able to find "words.txt"? 如果其他人使用该应用程序,该应用程序将无法找到“ words.txt”吗?

I want to load words into an array without having this massive chunk of code with 1000 ".add()" statements. 我想将单词加载到数组中,而不用1000条“ .add()”语句编写大量代码。

I'm using the version of eclipse that came with the ADT bundle provided by Android 我正在使用Android提供的ADT捆绑包随附的eclipse版本

If you need to keep only a list of words you can store it in an array under res of your application. 如果只需要保留单词列表,则可以将其存储在应用程序分辨率下的数组中。 This solution assumes that you need to keep only a list of words. 该解决方案假定您只需要保留单词列表。

create an xml file array.xml as, 创建一个xml文件array.xml,

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="words">
        <item>word1</item>
        <item>word2</item>
        <item>word3</item>
    </string-array>
</resources>

save this file in res/values/array.xml 将此文件保存在res / values / array.xml中

Get the words into an arrayList inside your activity class. 将单词放入活动类内的arrayList中。

String[] arrayOfWords= getResources().getStringArray(R.array.words);
List<String> arrayListOfWords= Arrays.asList(arrayOfWords);

Hope this meets your need. 希望这能满足您的需求。 But if you need to keeps the words as a txt file.You can put it in assets folder and read it from your activity. 但是如果需要将单词保留为txt文件,可以将其放在资产文件夹中并从活动中读取它。

将文件放在Assets文件夹中,然后可以使用AssetsManager从代码中检索或读取文件。

You need to put your file in assets folder of projects. 您需要将文件放在项目的资产文件夹中。 There is a demo for this, you can check it out. 有一个演示,您可以签出。 http://sunil-android.blogspot.in/2013/05/read-file-from-assets.html http://sunil-android.blogspot.in/2013/05/read-file-from-assets.html

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

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