【问题标题】:Copy txt files to array (word by word) with using fileChooser使用 fileChooser 将 txt 文件复制到数组(逐字)
【发布时间】:2018-12-01 12:28:13
【问题描述】:

伙计们,我在 Java 中同时使用 fileChooser 和文件阅读器时遇到了问题。我需要帮助。 使用 fileChooser 将 txt 文件逐字复制到数组(每个单词将保持不同的数组索引号)。

【问题讨论】:

  • 如果您不能同时考虑两者,一种方法是您可以使用 JFileChooser 获取文件的目录,然后使用您想要的任何方法读取该文件。

标签: java arrays copy filereader filechooser


【解决方案1】:

在 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.");
    }

在这里我打印出每个单词。您可以对存储在数组中的单词做任何事情。我希望这会有所帮助。

【讨论】:

  • 感谢您的帮助。我正在寻找。
猜你喜欢
  • 2012-03-22
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 2022-11-24
  • 2013-05-05
  • 1970-01-01
  • 2016-10-02
  • 2014-03-23
相关资源
最近更新 更多