0

我想要做的是当我单击一个按钮时,我从 USB 等便携式驱动器复制一些文件并将这些文件复制到我的本地驱动器,然后我读取我复制的所有 csv 文件并将它的值放在一个数组列表中并将其注入数据库,然后我可以删除这些文件,我想根据进程完成显示进程进度条。所以这就是我要做的:

           void main()
            {
             JButton btnTransfer = new JButton("Transfer");
                         Image transferIMG = ImageIO.read(new File("C:\\Users\\User\\Desktop\\images\\transfer.png"));
                         btnTransfer.setIcon(new ImageIcon(transferIMG));
                         btnTransfer.setPreferredSize(new Dimension(110, 90));
                         btnTransfer.setOpaque(false);
                         btnTransfer.setContentAreaFilled(false);
                         btnTransfer.setBorderPainted(false);
                         btnTransfer.setVerticalTextPosition(SwingConstants.BOTTOM);
                         btnTransfer.setHorizontalTextPosition(SwingConstants.CENTER);
                         btnTransfer.addActionListener(new ActionListener()
                         {
                              public void actionPerformed(ActionEvent e)
                              {
                                  File csvpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\csv");
                                  File htmlpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\html");
                                  String removepath = fileList1.getSelectedValue() + "\\salestablet\\report";

                                  if(csvpath.listFiles().length > 0 && htmlpath.listFiles().length > 0)
                                  {
                                       File[] csvarr = csvpath.listFiles();
                                       File[] htmlarr = htmlpath.listFiles();

                                       try 
                                       {
                                            copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
                                       } 
                                       catch (IOException e1) 
                                       {
                                           // TODO Auto-generated catch block
                                           e1.printStackTrace();
                                       }
                                 }
                              }
                         });

         JPanel ButtonCont = new JPanel(new GridLayout(4, 1, 5, 0));
                     ButtonCont.setBackground(Color.LIGHT_GRAY);

                     ButtonCont.add(btnTransfer);

         gui.add(ButtonCont , BorderLayout.EAST);

                     frame.setContentPane(gui);
                     frame.setExtendedState(Frame.MAXIMIZED_BOTH);  
                     frame.setMinimumSize(new Dimension(900, 100));
                     frame.pack();
                     frame.setLocationByPlatform(true);
                     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                     frame.setVisible(true);         
            }

      private static void copyFileUsingStream(File[] csvsources, File[] htmlsources, String dest, String removepath) throws IOException  
          {
               int count = 0;
               int MaxCount = countprocess(csvsources, htmlsources);

               progressBar =  new JProgressBar(0, MaxCount);
               progressBar.setStringPainted(true);

                InputStream is = null;
                OutputStream os = null;

                String csvfolderpath = dest + "\\csv";
                String htmlfolderpath = dest + "\\html";

                if(!(new File(csvfolderpath)).exists())
                {
                    (new File(csvfolderpath)).mkdirs(); //create csv folder;
                }

                if(!(new File(htmlfolderpath)).exists())
                {
                    (new File(htmlfolderpath)).mkdirs(); //create csv folder;
                }

                for(int i= 0; i < csvsources.length; i++) //copy all csv files to csv folder
                {
                    try 
                    {
                        is = new FileInputStream(csvsources[i]);
                        os = new FileOutputStream(csvfolderpath + "\\" + csvsources[i].getName());
                        byte[] buffer = new byte[1024];
                        int length;

                        while ((length = is.read(buffer)) > 0) 
                        {
                            os.write(buffer, 0, length);
                        }
                    }
                    finally
                    {
                        count += 1;
                        progressBar.setValue((count / MaxCount) * 100);
                        //progressBar.repaint();
                        //progressBar.revalidate();
                        progressBar.update(progressBar.getGraphics());

                        is.close();
                        os.close();
                    }
                }

                for(int i= 0; i < htmlsources.length; i++) //copy all html, images and css to html folder
                {
                    if(htmlsources[i].isFile())
                    {
                        try 
                        {
                            is = new FileInputStream(htmlsources[i]);
                            os = new FileOutputStream(htmlfolderpath + "\\" + htmlsources[i].getName());
                            byte[] buffer = new byte[1024];
                            int length;

                            while ((length = is.read(buffer)) > 0) 
                            {
                                os.write(buffer, 0, length);
                            }
                        }
                        finally
                        {
                            count += 1;
                            progressBar.setValue((count / MaxCount) * 100);
                            //progressBar.repaint();
                            //progressBar.revalidate();
                            progressBar.update(progressBar.getGraphics());

                            is.close();
                            os.close();
                        }
                    }
                    else if(htmlsources[i].isDirectory()) //for subfolder
                    {
                        String path = dest + "\\html\\" + htmlsources[i].getName();

                        if(!new File(path).exists())
                        {
                            (new File(path)).mkdirs(); //create subfolder;
                        }

                        File[] arr = (new File(htmlsources[i].getAbsolutePath())).listFiles();      

                        for(int j = 0; j < arr.length; j++)
                        {
                            if(arr[j].isFile())
                            {
                                try 
                                {
                                    is = new FileInputStream(arr[j]);
                                    os = new FileOutputStream(path + "\\" + arr[j].getName());
                                    byte[] buffer = new byte[1000000];
                                    int length;

                                    while ((length = is.read(buffer)) > 0) 
                                    {
                                        os.write(buffer, 0, length);
                                    }
                                }
                                finally
                                {
                                    if(htmlsources[i].getName().contains("images"))
                                    {
                                        count += 1;
                                        progressBar.setValue((count / MaxCount) * 100);
                                        //progressBar.repaint();
                                        //progressBar.revalidate();
                                        progressBar.update(progressBar.getGraphics());
                                    }

                                    is.close();
                                    os.close();
                                }
                            }
                        } 
                    }
                }

                ArrayList<String > DBValues = new ArrayList<String>(); //read all csv files values

                File f1 = new File(csvfolderpath); 
                for(int i = 0; i < f1.listFiles().length; i++)
                {
                     if(f1.listFiles()[i].isFile())
                     {
                        FileReader fl = new FileReader(f1.listFiles()[i]);
                        BufferedReader bfr = new BufferedReader(fl);    

                        for(int j = 0; j < 2; j++)
                        {
                            if(j == 1)
                            {
                                DBValues.add(bfr.readLine());

                                count += 1;
                                progressBar.setValue((count / MaxCount) * 100);
                                //progressBar.repaint();     
                                //progressBar.revalidate();
                                progressBar.update(progressBar.getGraphics());
                            }
                            else
                            {
                                bfr.readLine();
                            }
                        }
                        bfr.close();
                     }
                }

                /*for(int x = 0; x < DBValues.size(); x++)
                {
                    //System.out.println(DBValues.get(x));
                }*/

                //removing csv in local computer
                File f2 = new File(csvfolderpath); 
                File[] removelist = f2.listFiles();
                for(int x = 0; x < removelist.length; x++)
                {
                     if(removelist[x].isFile())
                     {
                         removelist[x].delete();

                         count += 1;
                         progressBar.setValue((count / MaxCount) * 100);
                        // progressBar.repaint();     
                         //progressBar.revalidate();
                            progressBar.update(progressBar.getGraphics());
                     }
                }

                //removing csv in device
                File f3 = new File(removepath + "\\csv");
                if(f3.isDirectory())
                {
                    removelist = f3.listFiles();

                   for(int y = 0; y < removelist.length; y++)
                   {
                       try
                       {
                           if(removelist[y].isFile())
                           {
                              //System.out.println(removelist[y].getName());
                              removelist[y].delete();
                              count += 1;
                              progressBar.setValue((count / MaxCount) * 100);
                              //progressBar.repaint();  
                             // progressBar.revalidate();
                            progressBar.update(progressBar.getGraphics());
                           }
                       }
                       catch(Exception e)
                       {
                          System.out.println(e);
                       }
                   }
                }

                //removing html and images in device
                File f4 = new File(removepath + "\\html");
                if(f4.isDirectory())
                {
                   removelist = f4.listFiles();

                   for(int z = 0; z < removelist.length; z++)
                   {
                       try
                       {
                           if(removelist[z].isFile())
                           {
                              removelist[z].delete();

                              count += 1;
                              progressBar.setValue((count / MaxCount) * 100);
                             // progressBar.repaint(); 
                             // progressBar.revalidate();
                            progressBar.update(progressBar.getGraphics());
                           }
                           else if(removelist[z].isDirectory())
                           {
                               if(removelist[z].getName().contains("images"))
                               {
                                   File[] subfolder = removelist[z].listFiles();

                                   for (int idx = 0; idx < subfolder.length; idx++)
                                   {
                                       if(subfolder[idx].isFile())
                                       {
                                          subfolder[idx].delete();

                                          count += 1;
                                          progressBar.setValue((count / MaxCount) * 100);
                                         // progressBar.repaint(); 
                                        //  progressBar.revalidate();
                                        progressBar.update(progressBar.getGraphics());
                                       }
                                   }
                               }
                           }
                       }
                       catch(Exception e)
                       {
                          System.out.println(e);
                       }
                   }
                }

                /*  JProgressBar progressBar = new JProgressBar();
                    progressBar.setValue(25);
                    progressBar.setStringPainted(true);*/
                    Border border = BorderFactory.createTitledBorder("Reading...");
                    progressBar.setBorder(border);


                gui.add(progressBar, BorderLayout.SOUTH);
                gui.repaint();
                gui.revalidate();


                // System.out.println(count);
            }

  private static int countprocess(File[] csv, File[] html_image)
  {
      int x = 0;
      int y = 0;
      int z = 0;

      for(int i = 0; i < csv.length; i++)
      {
          if(csv[i].isFile())
          {
              x += 1;
          }
      } //get total count of csv files throught loop

      for(int i = 0; i < html_image.length; i++)
      {
          if(html_image[i].isFile())
          {
              y += 1;
          }
          else if(html_image[i].isDirectory())
          {
              if(html_image[i].getName().contains("images"))
              {
                  File[] flist = html_image[i].listFiles();

                  for(int j = 0; j < flist.length; j++)
                  {
                      z += 1;
                  }
              }
          }  //get total count of html and images files throught loop
      }

      return ((4*x) + (2*y) + (2*z));
  }

所以我尝试通过设置它的值来刷新我的进度条值

progressBar.setValue((count / MaxCount) * 100);

但不知何故我无法让它工作,我的进度条没有显示它的进度,比如 1% 2% 3%.. 10% 等等.. 相反,它只在完成过程时显示 100%.. 我想念什么这里?注意:我也尝试过以这种方式设置我的进度条值progressBar.setValue(count);仍然没有运气。

4

2 回答 2

1

审查你的整个代码需要一段时间。但是,在你btnTransfer.addActionListeneractionPerformed函数中,你试图复制可能需要一段时间的流。任何类型的事件侦听器都在事件调度线程中执行。有关详细信息,请参阅此答案。

现在作为一个快速的解决方案:

  • 把你的copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);函数放在一个内联线程中:

       new Thread()
      {
       public void run()
       {
           copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
      }
    }.start();
    
    } 
    
  • 将您的进度更新JProgressBar放在里面SwingUtilities.invokeLater,并(count/MaxCount)通过将其中一个转换为 来进行计算double,如下所示:

    SwingUtilities.invokeLater(new Runnable() {
    
        @Override
        public void run() {
    
         count += 1;
         progressBar.setValue((int) (((double)count/ MaxCount) * 100));
        }
    });
    

由于count是函数的本地copyFileUsingStream函数,请尝试在您的类上下文中声明它以访问和更改。

SwingWorker更适合这种任务。

教程资源:

  1. 工作线程和 SwingWorker
  2. 如何在摇摆工人中使用进度条
  3. 使用 SwingWorker 的 ProgressBar 演示
于 2013-10-30T19:35:24.503 回答
0

您正在将进度条中的值设置为完成百分比。但是你的进度条的最大值实际上是项目的总数。

相反,您只需将进度条值设置为当前计数并摆脱 % 的计算。

就像是:

progressBar.setValue(count );

此外,您应该在 SwingWorker 线程中执行长时间运行的任务,这样您就不必强制重新绘制 GUI。

于 2013-10-30T15:56:02.803 回答