简体   繁体   中英

Read a text file to an array Java

I know there are many questions about reading text files here but I have gone through all of them and I think I'm having some difficulty with syntax or SOMETHING because nothing that I've been trying has been working at all.

What I'm attempting to do is this:

1) read a text file inputed by user 
2) copy each individual line into an array, so each line is its own element in the array

I feel like I am very close but for some reason I can't figure out exactly how to get it to work!

Here is the relevant code I have right now:

I keep getting out of bounds exceptions in three locations which I've marked off.

Been working on this for quite a while not sure what to do next! Any ideas?

import java.io.IOException;
import java.util.Scanner;


public class FindWords {

public static void main (String args[]) throws IOException{

    FindWords d = new Dictionary();
    ((Dictionary) d).dictionary();  //********* out of bounds here


}


/**
 * Validates and returns the dictionary inputed by the user.
 * 
 * @param
 * @return the location of the dictionary
 */
public static String getDict(){
    ///////////////////ASK FOR DICTIONARY////////////////////
    System.out.println("Please input your dictionary file");

    //initiate input scanner
    Scanner in = new Scanner(System.in);

    // input by user 
    String dictionary = in.nextLine();

    System.out.println("Sys.print: " + dictionary);


    //make sure there is a dictionary file
    if (dictionary.length() == 0){
        throw new IllegalArgumentException("You must enter a dictionary");
    }
    else return dictionary;
}

}

which calls on the class Dictionary:

import java.io.*;


public class Dictionary extends FindWords{

public void dictionary () throws IOException{

    String dict = getDict();

        String[] a = readFile(dict);  //********** out of bounds here

    int i = 0;
    while(a[i] != null){
        System.out.println(a[i]);
        i++;
    }

}





public static String[] readFile(String input) throws IOException{   


//read file
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(input)));

System.out.println ();

int count = 0;
String[] array = new String[count];
try{
while (br.readLine() != null){
    array[count] = br.readLine(); //********out of bounds here
    count++;
}
br.close();
}
catch (IOException e){

}
return array;

}

}

Thank you for looking!

Edit: Just fyi: I have my .txt file in the parent project folder.

Have you tried this?:

List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));

and then transform your list to an array if you want:

String[] myLines = lines.toArray(new String[lines.size()]);

You are initializing a zero-length array, hence the exception on the first iteration:

int count = 0;
String[] array = new String[count];

Since you probably don't know the expected size, work with a List instead:

List<String> list = new ArrayList<>();
String thisLine = null;
try{
    while ((thisLine = br.readLine()) != null) {
        list.add(thisLine);
    }
}

You can get the total size afterwards by:

list.size();

Or even better, go with morganos solution and use Files.readAllLines() .

You start with an array size of zero...

int count = 0;
String[] array = new String[count];

Several issues here :

  • In Java, you can't expand arrays, ie you have to know their length in advance when you instantiate them. Hence the ArrayOutOfBoundException. To make this easy, I suggest that you use an ArrayList instead.
  • In your while loop, you're making 2 calls to br.readLine() , so basically you're skipping one line out of 2.

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.

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