0

What i am trying to do is when i click a button, i copy some files from a portable drive like usb and copy those files to my local drive, then i read all csv files which i copied ealier and i put it's values in an arraylist and inject it to database, and then i can delete those files, and i want to show the process in progress bar based on process completion. so this is what i do :

           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));
  }

so i tried to refresh my progress bar value by setting it's value like this

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

but somehow i can't make it to work, my progress bar does not showing it's progress like 1% 2% 3%.. 10% and so on.. instead it's only show 100% when it's process completed.. what i miss here? note : i also have tried to set my progress bar value this way progressBar.setValue(count); still no luck.

NomNomNom
  • 811
  • 3
  • 12
  • 37

2 Answers2

1

Reviewing your whole code will take a while. But, inside your btnTransfer.addActionListener's actionPerformed function you are trying to copy stream which might take a while. Any kind of event listener is performed in event dispatch thread. Please refer to this answer for more details.

Now as a quick solution:

  • put your copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath); function inside a in-line thread:

       new Thread()
      {
       public void run()
       {
           copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
      }
    }.start();
    
    } 
    
  • Put your progress update of JProgressBar inside SwingUtilities.invokeLater and make the (count/MaxCount) computation by casting one of them to double, as follows:

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

as count is local to the copyFileUsingStream function, please try to declare it in your class context to access and change.

But SwingWorker is preferable for this kind of task.

Tutorial Resources:

  1. Worker Threads and SwingWorker
  2. How to use progress bars with swing worker
  3. ProgressBar Demo with SwingWorker
Community
  • 1
  • 1
Sage
  • 15,290
  • 3
  • 33
  • 38
  • @HendraLim, please be aware of the progress computation with `count/MaxCount` as i have indicated in the post – Sage Oct 31 '13 at 07:57
  • i have tried your suggestion, but still no luck. anyway it's working now, i am using double thread to make it work. anyway i am voting you up for good suggestion, thx. – NomNomNom Nov 01 '13 at 06:38
0

You are setting a value in your progress bar to a percent complete. But the max value of your progress bar is actually the total number of items.

Instead, you need to just set your progressbar value to your current count and get rid of the calculation for the %.

Something like:

progressBar.setValue(count );

Also you should be doing your long running task in a SwingWorker thread so that you don't have to force repainting of the GUI.

jzd
  • 23,473
  • 9
  • 54
  • 76
  • thanx, before my current code, i have tried to use progressBar.setValue(count ) ealier , but it did not work, so i thought i should calculate it manually. btw about "SwingWorker" can you show me how to do it? i am not really familiar with that, thanx before. – NomNomNom Oct 30 '13 at 16:17
  • You don't even have to get crazy with a SwingWorker. Just make sure the update to the progress bar happens on the swing rendering thread by wrapping the progress update in a Runnable, and hand that off to [SwingUtilities.invokeLater](http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater(java.lang.Runnable)) – David Oct 30 '13 at 16:34
  • @David, the problem is that the loading is happening on the EDT. It needs to be broken off into a SwingWorker from which he can call invokeLater as you recommended. – jzd Oct 30 '13 at 16:52