将文本文件读取到Java数组中

将文本文件读取到Java数组中,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,我知道这里有很多关于阅读文本文件的问题,但我已经把它们都看了一遍,我想我在语法或其他方面遇到了一些困难,因为我一直在尝试的东西都不起作用 我想做的是: 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 我觉得我很接近,但由于某种原因,我不能确切地知道如何让它工作 以下是我目前掌握的相关代码: 我

我知道这里有很多关于阅读文本文件的问题,但我已经把它们都看了一遍,我想我在语法或其他方面遇到了一些困难,因为我一直在尝试的东西都不起作用

我想做的是:

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
我觉得我很接近,但由于某种原因,我不能确切地知道如何让它工作

以下是我目前掌握的相关代码:

我一直在三个我标记的位置出现越界异常

这件事已经做了很长时间了,不知道下一步该怎么办!有什么想法吗

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;
}

}
它调用类字典:

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;

}

}
谢谢你的关注


编辑:仅供参考:我的.txt文件在父项目文件夹中

您正在初始化零长度数组,因此在第一次迭代时出现异常:

int count = 0;
String[] array = new String[count];
由于您可能不知道预期的大小,请使用列表:


或者更好的方法是使用morganos解决方案并使用Files.readAllLines。

从数组大小为零开始

int count = 0;
String[] array = new String[count];
你试过这个吗

List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
这里有几个问题:

在Java中,不能扩展数组,也就是说,在实例化数组时,必须提前知道它们的长度。因此出现了ArrayOutOfBoundException。为了方便起见,我建议您使用一个。 在while循环中,您对br.readLine进行了两次调用,因此基本上是跳过了2行中的一行。
int count = 0;
String[] array = new String[count];
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
String[] myLines = lines.toArray(new String[lines.size()]);