Google Tag Manager

Showing posts with label File. Show all posts
Showing posts with label File. Show all posts

2018/09/30

Expand the zip file selected by JFileChooser

Code

JButton button1 = new JButton("unzip");
button1.addActionListener(e -> {
  String str = field.getText();
  Path path = Paths.get(str);
  if (str.isEmpty() || Files.notExists(path)) {
    return;
  }
  String name = Objects.toString(path.getFileName());
  int lastDotPos = name.lastIndexOf('.');
  if (lastDotPos > 0) {
    name = name.substring(0, lastDotPos);
  }
  Path destDir = path.resolveSibling(name);
  try {
    if (Files.exists(destDir)) {
      String m = String.format(
          "<html>%s already exists.<br>Do you want to overwrite it?",
          destDir.toString());
      int rv = JOptionPane.showConfirmDialog(
          button1.getRootPane(), m, "Unzip", JOptionPane.YES_NO_OPTION);
      if (rv != JOptionPane.YES_OPTION) {
        return;
      }
    } else {
      if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.info("mkdir0: " + destDir.toString());
      }
      Files.createDirectories(destDir);
    }
    ZipUtil.unzip(path, destDir);
  } catch (IOException ex) {
    ex.printStackTrace();
  }
});
// ...
public static void unzip(Path zipFilePath, Path destDir) throws IOException {
  try (ZipFile zipFile = new ZipFile(zipFilePath.toString())) {
    Enumeration<? extends ZipEntry> e = zipFile.entries();
    while (e.hasMoreElements()) {
      ZipEntry zipEntry = e.nextElement();
      String name = zipEntry.getName();
      Path path = destDir.resolve(name);
      if (name.endsWith("/")) { // if (Files.isDirectory(path)) {
        log("mkdir1: " + path.toString());
        Files.createDirectories(path);
      } else {
        Path parent = path.getParent();
        if (Files.notExists(parent)) {
          log("mkdir2: " + parent.toString());
          Files.createDirectories(parent);
        }
        log("copy: " + path.toString());
        Files.copy(zipFile.getInputStream(zipEntry),
                   path, StandardCopyOption.REPLACE_EXISTING);
      }
    }
  }
}
//...
public static void zip(Path srcDir, Path zip) throws IOException {
  try (Stream<Path> s = Files.walk(srcDir).filter(Files::isRegularFile)) {
    List<Path> files = s.collect(Collectors.toList());
    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zip))) {
      for (Path f: files) {
        String relativePath = srcDir.relativize(f).toString();
        ZipEntry ze = new ZipEntry(relativePath.replace('\\', '/'));
        zos.putNextEntry(ze);
        Files.copy(f, zos);
      }
    }
  }
}

References

2011/11/28

JTable group directories first sorting

Code

// > dir /O:GN
// > ls --group-directories-first
class FileGroupComparator extends DefaultFileComparator {
  private static final long serialVersionUID = 1L;
  private final JTable table;
  public FileGroupComparator(JTable table, int column) {
    super(column);
    this.table = table;
  }

  @Override public int compare(File a, File b) {
    int flag = 1;
    List<? extends TableRowSorter.SortKey> keys =
        table.getRowSorter().getSortKeys();
    if (!keys.isEmpty()) {
      TableRowSorter.SortKey sortKey = keys.get(0);
      if (sortKey.getColumn() == column &&
          sortKey.getSortOrder() == SortOrder.DESCENDING) {
        flag = -1;
      }
    }
    if (a.isDirectory() && !b.isDirectory()) {
      return -1 * flag;
    } else if (!a.isDirectory() && b.isDirectory()) {
      return 1 * flag;
    } else {
      return super.compare(a, b);
    }
  }
}

References

2011/08/29

FileSystemTree with JCheckBox

Code

class CheckBoxNodeEditor extends TriStateCheckBox implements TreeCellEditor {
  private final FileSystemView fileSystemView;
  private final JPanel panel = new JPanel(new BorderLayout());
  private DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
  private File file;

  public CheckBoxNodeEditor(FileSystemView fileSystemView) {
    super();
    this.fileSystemView = fileSystemView;
    this.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent e) {
        stopCellEditing();
      }
    });
    panel.setFocusable(false);
    panel.setRequestFocusEnabled(false);
    panel.setOpaque(false);
    panel.add(this, BorderLayout.WEST);
    this.setOpaque(false);
  }

  @Override public Component getTreeCellEditorComponent(
      JTree tree, Object value, boolean isSelected, boolean expanded,
      boolean leaf, int row) {
    JLabel l = (JLabel) renderer.getTreeCellRendererComponent(
      tree, value, true, expanded, leaf, row, true);
    l.setFont(tree.getFont());
    setOpaque(false);
    if (value instanceof DefaultMutableTreeNode) {
      this.setEnabled(tree.isEnabled());
      this.setFont(tree.getFont());
      Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
      if (userObject instanceof CheckBoxNode) {
        CheckBoxNode node = (CheckBoxNode) userObject;
        if (node.status == Status.INDETERMINATE) {
          setIcon(new IndeterminateIcon());
        } else {
          setIcon(null);
        }
        file = node.file;
        l.setIcon(fileSystemView.getSystemIcon(file));
        l.setText(fileSystemView.getSystemDisplayName(file));
        setSelected(node.status == Status.SELECTED);
      }
      // panel.add(this, BorderLayout.WEST);
      panel.add(l);
      return panel;
    }
    return l;
  }

  @Override public Object getCellEditorValue() {
    return new CheckBoxNode(file, isSelected() ? Status.SELECTED : Status.DESELECTED);
  }

  @Override public boolean isCellEditable(EventObject e) {
    if (e instanceof MouseEvent && e.getSource() instanceof JTree) {
      MouseEvent me = (MouseEvent) e;
      JTree tree = (JTree) e.getSource();
      TreePath path = tree.getPathForLocation(me.getX(), me.getY());
      Rectangle r = tree.getPathBounds(path);
      if (r == null) {
        return false;
      }
      Dimension d = getPreferredSize();
      r.setSize(new Dimension(d.width, r.height));
      if (r.contains(me.getX(), me.getY())) {
        // if (file == null && System.getProperty("java.version").startsWith("1.7.0")) {
        //   System.out.println("XXX: Java 7, only on first run\n" + getBounds());
        //   setBounds(new Rectangle(0, 0, d.width, r.height));
        // }
        return true;
      }
    }
    return false;
  }

  @Override public void updateUI() {
    super.updateUI();
    if (panel != null) {
      panel.updateUI();
    }
    // 1.6.0_24 bug??? @see 1.7.0 DefaultTreeCellRenderer#updateUI()
    renderer = new DefaultTreeCellRenderer();
  }
// ...

References