如何使用Swings Applications上传多个文件?

时间:2010-07-15 12:26:49

标签: java swing

我试图在swings应用程序中上传多个文件。我已经声明了一个数组来保存所选文件的值,但是当我点击上传按钮时,只有1个文件被上传。如何将所有选定的文件上传到数据库?

打开和上传文件的代码是....

 public void openFile() 
 {
      JFileChooser jfc = new JFileChooser();
      jfc.setMultiSelectionEnabled(true);// added line
      int result = jfc.showOpenDialog(this);
      if(result == JFileChooser.CANCEL_OPTION) return;
      try {
            ArrayList<String> FileData = new ArrayList<String>();
            File[] file = jfc.getSelectedFiles();
            String s=""; int c=0;
            for(int i=0;i<file.length;i++) //added
            {  
              jep.setText(file[i].toString()); // added
            }
            return FileData;
          } 
          catch (Exception e) 
          {
             JOptionPane.showMessageDialog(this,e.getMessage(),
            "File error",JOptionPane.ERROR_MESSAGE);
          }
   }

2 个答案:

答案 0 :(得分:0)

    // get list of selected files
    File[] file = jfc.getSelectedFiles();
    String s=""; int c=0;
    for(int i=0;i<file.length;i++) //added
    {  
      // The toString will just return you back the path of the file object times the number of bytes in the file.
      jep.setText(file[i].toString()); // added
    }
    return FileData;

此代码无效。如果您希望方法将给定文件名的文件读入字符串数组,那么您将需要:

   /**
    * Read entire contents of a text file.
    *
    * @param fileName Text file name
    * @return ArrayList of String (line) elements
    * @throws FileNotFoundException
    * @throws IOException
    */
   public static ArrayList readTextFile( String fileName )
      throws FileNotFoundException, IOException
   {
      ArrayList lines = new ArrayList();
      BufferedReader in = null;
      try
      {
         in = new BufferedReader( new FileReader( fileName ));
         String line;
         while ( ( line = in.readLine()) != null )
         {
            lines.add( line );
         }
      }
      finally
      {
         if ( in != null )
         {
            try
            {
               in.close();
            }
            catch ( IOException ex )
            {
            }
         }
      }
      return lines;
   }

由于您想要读入多个文件的内容,只需在循环中执行此操作并单独执行每个文件。如果将它全部加载到内存中,可能会遇到问题。

答案 1 :(得分:0)

您尚未通过“上传多个文件”明确定义您的实际含义。我假设您希望将多个文本文件的内容一个接一个地加载到单个JEditorPane中。如果是这种情况,Romain的答案会向您显示加载单个文件的示例。 您的代码实际上正在做的是循环遍历File个对象的数组并设置其路径(这是toStringFile上返回的内容)作为文本在编辑器窗格中。每一个都覆盖最后一个,这就是为什么你最终得到一个文件路径。 我可能还会建议您弹出JFileChooser时限制文件,用户可以选择特定文件类型(例如txt,html)。

相关问题