我知道这里有很多有关读取文本文件的问题,但是我已经遍历了所有这些问题,并且我认为我在语法或某些方面遇到了一些困难,因为我一直在尝试的所有内容都没有起作用。
我正在尝试做的是这样的:
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()]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句