简体   繁体   中英

Putting items from file into a string array

How do I input the items from a file into a String array?? This is what i have so far, but it keeps displaying null as a result! Anyone know what the problem may be?

  public static void main(String[] args) {

    File inFile = new File("GUGU.txt"); // connect the program and file
    String input;

    int numLines = 0;
    String[] words = new String[50];//large enough to store 50 names
    int big = 0;

    String firstLine = "";
    if (inFile.exists() && inFile.length() != 0) {
        try {
            System.out.println("File read");
            BufferedReader in = new BufferedReader(new FileReader(inFile));
            input = in.readLine();
            while (input != null) {  // continue while not end of file

                if (input.length() > big) {
                    big = input.length();
                }
                words[numLines] = input;

                numLines++;
                input = in.readLine();
                System.out.println(words[numLines]); 
            }

        } catch (java.io.IOException e) {
            System.out.println(e);
        }
    }
}

Move the println to before you increment the numlines variable. You are printing whatever is next in your array, which is null since the array is empty.

Hoping its not an assignment question. If you need to read file into a string array, you can do this in mere 3-4 lines of code. Apache fileutils class provides lots of flexibilties like this.

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