文件转换期间的Java ProgressMonitorInputStream

时间:2017-09-02 08:32:42

标签: java swing progressmonitor

我无法让Java Swing进度监视器正常工作。下面的脚本转换所选目录中的所有文件。循环期间从不显示进度条窗口。可能我必须为ProgressMonitorInputStream提供更多提示,例如max和min值。我无法单独解决这个问题,并会感激任何帮助。

public class csvtoxls {

    public static void main() throws IOException {
//here you enter the path to your directory.
//for example: Path workDir = Paths.get("C:\\Users\\Kamil\Desktop\\csvtoxlspython\\Nowy folder (2)")
        JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
        jfc.setDialogTitle("Wybierz folder do konwersji: ");
        jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        jfc.setAcceptAllFileFilterUsed(false);
        int returnValue = jfc.showSaveDialog(null);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            if (jfc.getSelectedFile().isDirectory()) {
                System.out.println("You selected the directory: " + jfc.getSelectedFile());

String z;
    //@SuppressWarnings("deprecation")
    //Path workDir = jfc.getCurrentDirectory().toPath();
    //Path workDir = FileSystems.getDefault().getPath(jfc.getCurrentDirectory());
    Path workDir = Paths.get(gui.pickPath(jfc));
    System.out.println(workDir);

//the if checks whether the directory truly exists
    if (!Files.notExists(workDir )) {;

//this part stores all files withn the directory in a list
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(workDir )) {

            for (Path path : directoryStream) {



                @SuppressWarnings("deprecation")
                    ArrayList<ArrayList<String>> allRowAndColData = null;
                    ArrayList<String> oneRowData = null;
                    Path fName = workDir;
                    String currentLine;
                    FileInputStream fis = new FileInputStream(path.toString());
                    DataInputStream myInput = new DataInputStream(fis);

                    ProgressMonitorInputStream pm = new ProgressMonitorInputStream(null ,"Reading the big file", fis);


                    int c;
                    while((c=pm.read()) != -1) {



                        int i = 0;
                        allRowAndColData = new ArrayList<ArrayList<String>>();
                        while ((currentLine = myInput.readLine()) != null) {
                            oneRowData = new ArrayList<String>();
                            String oneRowArray[] = currentLine.split(";");
                            for (int j = 0; j < oneRowArray.length; j++) {
                                oneRowData.add(oneRowArray[j]);
                            }
                            allRowAndColData.add(oneRowData);
                            System.out.println();
                            i++;


                    }

                 try {

                     HSSFWorkbook workBook = new HSSFWorkbook();
                     HSSFSheet sheet = workBook.createSheet("sheet1");
                     for (int i1 = 0; i1 < allRowAndColData.size(); i1++) {
                       ArrayList<?> ardata = (ArrayList<?>) allRowAndColData.get(i1);
                       HSSFRow row = sheet.createRow((short) 0 + i1);
                       for (int k = 0; k < ardata.size(); k++) {
                            System.out.print(ardata.get(k));
                            HSSFCell cell = row.createCell((short) k);
                            cell.setCellValue(ardata.get(k).toString());


                       }
                       System.out.println();

                     }

                // Write the output to a file
                z = path.toString();
                z = z = z.substring(0, z.lastIndexOf('.'));
                FileOutputStream fileOutputStream = new FileOutputStream(z + ".xls");
                workBook.write(fileOutputStream);
                fileOutputStream.close();

            }

        catch (IOException e) {
            System.out.println(e.getMessage());
        } 

        finally {

        // ... cleanup that will execute whether or not an error occurred ...
        }

                    }
    }
    }
}
}
        }
    }
}

1 个答案:

答案 0 :(得分:1)

假设您的实际代码为works correctly,并且如How to Use Progress Bars中所述,ProgressMonitorInputStream使用的ProgressMonitor仅在延迟后显示,默认为500毫秒。如果您的工作单位足够短,则可能不会显示对话框,但您可以根据需要缩短延迟时间:

pm.getProgressMonitor().setMillisToPopup(1);

image

在下面的示例中,

  • SwingWorker在后台处理该文件。

  • 短暂延迟和冗长的文件会使对话框按预期显示。

  • try-with-resources语句可确保在语句结束时关闭每个资源。

代码,改编自answer

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.SwingWorker;

/**
 * @see https://stackoverflow.com/a/46019237/230513
 * @see https://stackoverflow.com/a/26394738/230513
 */
public class ProgressBarDemo extends JFrame {

    private JButton button;

    ProgressBarDemo() {
        button = new JButton("Click me!");
        ButtonActionListener bal = new ButtonActionListener();
        button.addActionListener(bal);
        this.getContentPane().add(button);
    }

    public void go() {
        this.setLocationRelativeTo(null);
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    private void processFile() {
        File file = new File("/usr/share/dict/words");
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis);) {
            ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
                this, "Reading " + file.getAbsolutePath(), bis);
            pmis.getProgressMonitor().setMillisToPopup(1);
            int i = 0;
            while ((i = pmis.read()) != -1) {
                System.out.print((char) i);
            }
            pmis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class ButtonActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            button.setEnabled(false);
            SwingWorker worker = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    processFile();
                    return null;
                }

                @Override
                protected void done() {
                    button.setEnabled(true);
                }
            };
            worker.execute();
        }
    }

    public static void main(String[] args) {
        ProgressBarDemo demo = new ProgressBarDemo();
        demo.go();
    }
}