2016-03-23 43 views
2

我正在編寫一個鞦韆應用程序。這裏的任務是從給定的URL下載文件,然後得到它們的計數。該程序沒有問題/錯誤。追加數據,因爲我進步而不是一次做到這一點

的問題是我在框架已經一個testarea,當file 1下載我想要的文本區域顯示downloaded file 1當文件2完成downloaded file 1等等...

在我的計劃

目前消息顯示,但一次。我的意思是如果我有10個文件,它顯示。

downloaded file 1 
downloaded file 2 
. 
. 
. 
. 
. 
downloaded file 10 

但是,只有在下載了所有10個文件後才顯示。要查看是否還有其他問題,我在textarea代碼的下方添加了0​​。令我驚訝的是,sysout s打印10次,我的意思是每次處理文件時,都會觸發,但textarea會一次附加所有數據。

以下是我的代碼。

GuiForPDFs

import java.awt.BorderLayout; 

public class GuiForPDFs extends JFrame { 

    private JPanel contentPane; 
    private JTextField srcTextField; 
    private JTextArea textArea; 

    /** 
    * Launch the application. 
    */ 
    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       try { 
        GuiForPDFs frame = new GuiForPDFs(); 
        frame.setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    /** 
    * Create the frame. 
    */ 
    FileDownloadTest downloadTest = new FileDownloadTest(); 

    public GuiForPDFs() { 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setBounds(100, 100, 552, 358); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null); 

     srcTextField = new JTextField(); 
     srcTextField.setBounds(10, 26, 399, 20); 
     contentPane.add(srcTextField); 
     srcTextField.setColumns(10); 

     JButton srcBtn = new JButton("Source Excel"); 
     srcBtn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       JFileChooser fChoose = new JFileChooser(); 
       if (fChoose.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
        srcTextField.setText(fChoose.getSelectedFile().getAbsolutePath()); 
       } else { 
        System.out.println("No Selection"); 
       } 
      } 
     }); 

     textArea = new JTextArea(); 
     textArea.setEditable(false); 
     textArea.setBounds(10, 106, 516, 203); 
     contentPane.add(textArea); 

     srcBtn.setBounds(419, 25, 107, 23); 
     contentPane.add(srcBtn); 

     JButton dNcButton = new JButton("Process"); 
     dNcButton.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       try { 
        downloadTest.fileDownloadTest(srcTextField.getText(), textArea); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     }); 
     dNcButton.setBounds(212, 70, 89, 23); 
     contentPane.add(dNcButton); 

    } 
} 

FileDownloadTest

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.net.MalformedURLException; 
import java.net.URL; 

import javax.swing.JTextArea; 

import org.apache.commons.io.FileUtils; 
import org.apache.pdfbox.pdmodel.PDDocument; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.xssf.usermodel.XSSFCell; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 

public class FileDownloadTest { 

    public void fileDownloadTest(String src, JTextArea textArea) throws IOException, InterruptedException { 
     String path = src; 
     FileInputStream fin = new FileInputStream(new File(path)); 
     XSSFWorkbook workbook = new XSSFWorkbook(fin); 
     XSSFSheet sheet = workbook.getSheetAt(0); 
     int rows = sheet.getPhysicalNumberOfRows(); 
     System.out.println("rows are " + rows); 
     XSSFCell cell; 
     // Make sure that this directory exists 
     String dirName = src.substring(0, src.lastIndexOf("\\")); 
     File f = new File(dirName); 
     if (!f.exists()) { 
      f.mkdir(); 
     } 
     System.out.println(f.getAbsolutePath() + " is Directory Name " + src + " is the file"); 
     for (int i = 1; i < rows; i++) { 
      XSSFCell url = sheet.getRow(i).getCell(0); 
      String URLString = url.toString(); 
      cell = sheet.getRow(i).getCell(7); 
      String fileName = URLString.substring(URLString.lastIndexOf("/") + 1); 
      int pageNumbers = downloadFiles(dirName, url.toString().replace("http", "https")); 
      if (cell == null) { 
       cell = sheet.getRow(i).createCell(1); 
      } 
      cell.setCellType(Cell.CELL_TYPE_NUMERIC); 
      cell.setCellValue(pageNumbers); 
      FileOutputStream fileOut = new FileOutputStream(path); 
      workbook.write(fileOut); 
      fileOut.close(); 
      textArea.append("downloaded " + fileName + "\n"); 
      System.out.println("Done"); 
     } 
     workbook.close(); 
     fin.close(); 

    } 

    public static int downloadFiles(String dirName, String urlString) { 
     System.out.println("Downloading \'" + urlString + "\' PDF document..."); 
     String fileName = urlString.substring(urlString.lastIndexOf("/") + 1); 
     System.out.println(fileName + " is file name"); 
     try { 
      saveFileFromUrlWithJavaIO(dirName + "\\" + fileName, urlString); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     System.out.println("Downloaded \'" + urlString + "\' PDF document..."); 
     int pageNumber = 0; 
     try { 
      pageNumber = getNoOfPages(dirName + "\\" + fileName); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return pageNumber; 
    } 

    public static int getNoOfPages(String fileName) throws IOException { 
     PDDocument document = PDDocument.load(new File(fileName)); 
     int numberOfPages = document.getNumberOfPages(); 
     return numberOfPages; 
    } 

    public static void saveFileFromUrlWithJavaIO(String fileName, String fileUrl) 
      throws MalformedURLException, IOException { 
     BufferedInputStream in = null; 
     FileOutputStream fout = null; 
     try { 
      in = new BufferedInputStream(new URL(fileUrl).openStream()); 
      fout = new FileOutputStream(fileName); 

      byte data[] = new byte[1024]; 
      int count; 
      while ((count = in.read(data, 0, 1024)) != -1) { 
       fout.write(data, 0, count); 
      } 
     } finally { 
      if (in != null) 
       in.close(); 
      if (fout != null) 
       fout.close(); 
     } 
    } 

    public static void saveFileFromUrlWithCommonsIO(String fileName, String fileUrl) 
      throws MalformedURLException, IOException { 
     FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName)); 
    } 

} 

請讓我知道我怎麼能解決這個問題。

感謝

+1

我沒有完全閱讀你的代碼,但你可能做的EDT(事件調度線程),這是負責更新用戶界面,並通過你的行動受阻。使用SwingWorker或類似的東西。 – Thomas

+0

提示:你有一個單獨的課程來測試你的東西真是太棒了。但是不要寫靜態電源()來做測試。轉向Junit;並編寫單元測試。這就是你如何在2016年進行測試。static main就像是1999. – GhostCat

+1

閱讀[swing中的併發](https://docs.oracle。com/javase/tutorial/uiswing/concurrency /) –

回答

1

以上說法是正確的,你是在美國東部時間添加文本到文本區的時候。這是因爲您正在撥打下載Test.fileDownloadTestdNcButton ActionListener實施。

擺脫美國東部時間是一個很好的做法,你有一個長時間的運行操作來執行,並經常給出下載文件作爲你不想在美國東部時間做的事情的例子。

網上有很多關於如何擺脫美國東部時間的資源,包括許多在這個偉大的網站;

On Event Dispatch Thread---want to get off of it

Make thread run on non EDT (event dispatch thread) thread from EDT

0

至於其他意見,你只需要保留UI相關的任務上的EDT。否則,如果您的用戶正在下載100個文件,則UI將鎖定,直到下載任務完成。 SwingWorker是Swing應用程序的完美課程。下面是一個簡單的例子:

// Run your FileDownloadTest inside a SwingWorker 
// or have the class extend SwingWorker 
new SwingWorker<Void, String>() { 

    @Override 
    protected Void doInBackground() throws Exception { 
     //Perform downloading here (done off the EDT) 
     //Call publish(downloadedFileName) to be sent to the process method() 
     return null; 
    } 

    @Override 
    protected void process(List<String> chunks) { 
     // Modify textArea (done on the EDT) 
     StringBuilder downloadedFiles = new StringBuilder(); 
     for (String fileName : chunks) { 
      downloadedFiles.append("downloaded" + fileName + "\n"); 
     } 
     textArea.setText(downloadedFiles); 
    } 

    @Override 
    protected void done() { 
     //Anything you want to happen after doInBackground() finishes 
    } 
}.execute(); 
+0

嗨,朋友,在這裏我正在做一些excel數據操作,它在'fileDownloadTest()'內完成,一次完成,它不像我處理一個並返回值和過程2並返回值。 – Rakesh

+0

您可以在文件下載後調用'publish(fileName)',然後由SwingWorker將其發送到'process()'方法。這允許''textArea'在每個文件從'downloadFiles()'方法下載後被更新。 – apicellaj

+0

對不起,我找不到你。我的問題是我在我的班級中有一個循環,通過Excel中的單元格循環。並且在那裏完成操作,並且將上面的代碼粘貼到我的Swing類'GuiForPDFs'中,如果您不介意,可以創建與我需要更改的地方相同的地方,我正在學習和工作在鞦韆上 – Rakesh

相關問題