我在Java上同时使用fileChooser和File Reader遇到问题。我需要帮助。 使用fileChooser逐个单词地将txt文件复制到数组中(每个单词将保留不同的数组索引号)。
答案 0 :(得分:0)
将此内容写入actionPerformed方法中:
final JFileChooser fc = new JFileChooser("E://");
int returnVal = fc.showOpenDialog(this);
System.out.println(returnVal);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
String p = file.getPath();
try(BufferedReader bufRead = new BufferedReader(new FileReader(p)))
{
StringBuilder sb = new StringBuilder();
String s = "";
while((s=bufRead.readLine())!=null)
{
sb.append(s+" ");
}
String[] words= sb.toString().split(" ");
for(String a:words)
{
System.out.println(a);// printing out each word
}
}
catch(FileNotFoundException e)
{
System.out.println("File not found : "+e.getMessage());
}
catch(IOException ex)
{
System.out.println("Exception : "+ex.getMessage());
}
}
else
{
System.out.println("Open command cancelled by user.");
}
我在这里打印出每个单词。您可以对存储在数组中的单词执行任何操作。我希望这会有所帮助。