我知道这里有很多关于阅读文本文件的问题,但我已经完成了所有这些问题,我认为我在语法或其他方面遇到了一些困难,因为我一直在尝试的任何东西都不起作用。
我正在尝试做的是:
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;
}
}
它调用类 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 文件位于父项目文件夹中。
最佳答案
你试过这个吗?:
List<String> lines = Files.readAllLines(Paths.get("/path/to/my/file.txt"));
然后根据需要将列表转换为数组:
String[] myLines = lines.toArray(new String[lines.size()]);
关于java - 将文本文件读取到数组 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26400045/