所以我试图使用JFile选择器从.txt文件中读取字符串并将它们保存到数组中。我虽然我有一个正确的设置,但问题是什么都没有被放入数组,因为当我显示数组时,它都是空的。我是java的新手,所以我对使用JFile选择器并不熟悉。窗口弹出,一切都让我选择一个文件,所以我认为它有点工作。另外,如果你能向我解释一下所有关于JFile选择器的代码意味着什么,我将非常感激,我所拥有的大部分内容来自视频,在线和书籍,我有点理解它,但我肯定需要进一步解释。
import java.io.*;
import java.util.Scanner; // All My imports
import javax.swing.*;
public class SpellChecker // I am creating a spell checker
{
static String check[] = new String[50]; // My array to save all of the strings in a file
static int index = 0; // index will incremented whenever a string is added to the array
public static void main(String args[])
{
getFile(); // Method call that opens file and saves all the data to the array
for(int i = 0; i < check.length - 1; i++) // outputting the array
{
System.out.println(check[i]);
}
}
public static void getFile()
{
JFileChooser chooser;
File infile, directory;
int status;
String wordToCheck;
chooser = new JFileChooser( );
status = chooser.showOpenDialog(null);
if(status == JFileChooser.APPROVE_OPTION)
{
infile = chooser.getSelectedFile();
directory = chooser.getCurrentDirectory();
try
{
infile = new File(chooser.getSelectedFile().getAbsolutePath());
Scanner scanner = new Scanner(infile);
while(scanner.hasNext())
{
wordToCheck = scanner.next();
if(index == check.length)
{
String tempAr[] = new String[check.length*2];
for(int i = 0; i < index; i++)
{
tempAr[i] = check[i];
}
check = tempAr;
}
check[index] = wordToCheck;
index++;
}
scanner.close();
}
catch(IOException e)
{
System.out.println("Error");
}
}
else
{
System.out.println("Open File dialog canceled");
}
}