0

I can't belive I have to ask for such a simple problem but it seems that I can't find a solution. I have 10 names in a txt file and I want to create a String array with that names. The names are disposed as 1 name per line so there are 10 lines in total. I have tried this code

String[] txtToString() throws IOException {

    Scanner s = null;
    String[] string = new String[10];
    int count = 0;

    try {
        s = new Scanner(new BufferedReader(new FileReader(
                "file:///android_res/raw/words.txt")));

        while (s.hasNext()) {
            count++;
            string[count] = s.next();
        }
    } finally {
        if (s != null) {
            s.close();
        }
    }
    return string;
}

But it didn't work. I've tried also putting just "words.txt" as file path but still nothing. Thanks for the help. P.s. for some unknown reason I can't import java.nio.file.Files so it must be something that don't use that import. Thanks again.

Ardi
  • 23
  • 4
  • 1
    "didn't work" *How* did your code not work? We can't read your mind. – awksp Jul 06 '14 at 22:02
  • Try `Scanner` object with `hasNextLine()`/`nextLine()` methods, assuming that your file path is correct. – PM 77-1 Jul 06 '14 at 22:02
  • The problem is opening the file or reading the lines? Is `IOException` thrown? This may help, by the way: http://stackoverflow.com/questions/5868369/how-to-read-a-large-text-file-line-by-line-using-java – Hugo Sousa Jul 06 '14 at 22:02
  • Nope nothing worked , I've tried hasNextLine/nextLine but still nothing. I'm just trying to set to a textView the second element of the txt but I can't see anything.. And I don't see any IOExepton on logcat – Ardi Jul 06 '14 at 22:20
  • yes now I'm getting fileNotFoundException but the file is there :S – Ardi Jul 06 '14 at 22:50

3 Answers3

1

Try interchanging these two lines:

count++;
string[count] = s.next();

At the moment your count variable is going from 1 to 10, instead of 0 to 9 like you want it to.

Carmeister
  • 208
  • 2
  • 8
  • yes thanks for the notation , I corrected it as it was obviously wrong but I still can't make work the code – Ardi Jul 06 '14 at 22:21
0

try this

while (s.hasNext()) {
    string[count++] = s.next();
}
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

ok I solved utilizing that method :

String[] txtToString() {
    String[] string = new String[10];
    int count = 0;
    try {
        Resources res = getResources();
        InputStream in = res.openRawResource(R.raw.words);

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));

        String line;

        while ((line = reader.readLine()) != null) {
            string[count] = line;
            count++;
        }

    } catch (Exception e) {
        // e.printStackTrace();

    }
    return string;
}

that returns exaclty a string array of 10 elements from the txt file "words.txt"

Ardi
  • 23
  • 4