簡體   English   中英

將文本文件讀取到數組Java

[英]Read a text file to an array Java

我知道這里有很多有關讀取文本文件的問題,但是我已經遍歷了所有這些問題,我認為我在語法或某些方面遇到了一些困難,因為我一直在嘗試的所有內容都沒有起作用。

我正在嘗試做的是這樣的:

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()]);

您正在初始化一個零長度的數組,因此第一次迭代是一個例外:

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

由於您可能不知道預期的大小,請改用List

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

您可以通過以下方式獲得總大小:

list.size();

甚至更好的是,使用morganos解決方案並使用Files.readAllLines()

您從零開始的數組大小開始...

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

這里有幾個問題:

  • 在Java中,您不能擴展數組,即在實例化它們時必須事先知道它們的長度。 因此,ArrayOutOfBoundException。 為了簡化此操作,建議您改用ArrayList
  • while循環中,您要對br.readLine()進行2次調用,因此基本上是從2中跳過一行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM