Description
It is a memory management java application use to free the memory of the computer and delete the duplicate files and has many more options.
//package home;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
public class FileManager {
/** Title of the application */
public static final String APP_TITLE = "FileMan";
/** Used to open/edit/print files. */
private Desktop desktop;
/** Provides nice icons and names for files. */
private FileSystemView fileSystemView;
/** currently selected File. */
private File currentFile;
/** Main GUI container */
private JPanel gui;
/** File-system tree. Built Lazily */
private JTree tree;
private DefaultTreeModel treeModel;
/** Directory listing */
private JTable table;
private JProgressBar progressBar;
/** Table model for File[]. */
private FileTableModel fileTableModel;
private ListSelectionListener listSelectionListener;
private boolean cellSizesSet = false;
private int rowIconPadding = 6;
/* File controls. */
private JButton openFile;
//private JButton printFile;
//private JButton editFile;
private JButton deleteFile;
private JButton newFile;
//private JButton copyFile;
private JButton delTempFolder;
private JButton deleteAll;
/* For search option. */
JTextField search_files;
JButton btn_search, btn_reset, btn_delete;
static Vector v;
String s_list[] = new String[100];
int count = 0;
/* OS details. */
private JButton osDetails;
/* Drive Details */
private JButton driveDetails;
/* File details. */
private JLabel fileName;
private JTextField path;
private JLabel date;
private JLabel size;
private JCheckBox readable;
private JCheckBox writable;
private JCheckBox executable;
private JRadioButton isDirectory;
private JRadioButton isFile;
/* GUI options/containers for new File/Directory creation. Created lazil
y. */
private JPanel newFilePanel;
private JRadioButton newTypeFile;
private JTextField name;
public Container getGui() {
if (gui == null) {
gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
fileSystemView = FileSystemView.getFileSystemView();
desktop = Desktop.getDesktop();
JPanel detailView = new JPanel(new BorderLayout(3, 3));
// fileTableModel = new FileTableModel();
JPanel search_panel = new JPanel();
search_files = new JTextField(30);
btn_search = new JButton("Search");
btn_reset = new JButton("Reset");
btn_delete = new JButton("delete");
search_panel.add(search_files);
search_panel.add(btn_search);
search_panel.add(btn_reset);
search_panel.add(btn_delete);
detailView.add(search_panel, BorderLayout.NORTH);
btn_search.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
File f = new File("C:\\");
File[] roots = f.listRoots();
// Create a vector of found files
v = new Vector();
// Print the search starting
System.out
.println("\nStarting sea
rch....\n-------------------------\n");
// Go search args[1] (2nd arg) in dir f
for (int i = 0; i < roots.length; i++) {
search(roots, search_files.ge
tText().toString());
}
File[] f_search = new File[v.size()];
v.copyInto(f_search);
System.out.println("\nResults");
System.out
.println("--------------
----------------------------\n");
// Loop till end of size
int i = 0;
for (File k : f_search) {
s_list = k.getAbsolutePath();
System.out.println("" + s_list[i
]);
count++;
i++;
setFileDetails(k);
}
setTableData(f_search);
}
});
btn_reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
search_files.setText("");
}
});
/* DELETION */
btn_delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int result = JOptionPane.showConfirmDial
og(gui,
"Are you sure you want t
o delete this file?", "Delete File",
JOptionPane.ERROR_MESSAG
E);
if (result == JOptionPane.OK_OPTION) {
try {
search_files.setText(""
+ path.getText().toString());
File f_delete = new File
("" + path.getText().toString());
System.out.println(f_del
ete.delete());
showErrorMessage("DELETE
D IF", "Delete Failed");
}
catch (Throwable t) {
showThrowable(t);
showErrorMessage(t.getMe
ssage(), "Delete Failed");
}
}
gui.repaint();
}
});
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTI
ON);
table.setAutoCreateRowSorter(true);
table.setShowVerticalLines(false);
listSelectionListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent lse)
{
int row = table.getSelectionModel().getL
eadSelectionIndex();
setFileDetails(((FileTableModel) table.g
etModel())
.getFile(row));
}
};
table.getSelectionModel().addListSelectionListener(
listSelectionListener);
JScrollPane tableScroll = new JScrollPane(table);
Dimension d = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(new Dimension((int) d.getWi
dth(),
(int) d.getHeight() / 2));
detailView.add(tableScroll, BorderLayout.CENTER);
// the File tree
DefaultMutableTreeNode root = new DefaultMutableTreeNode
();
treeModel = new DefaultTreeModel(root);
TreeSelectionListener treeSelectionListener = new TreeSe
lectionListener() {
public void valueChanged(TreeSelectionEvent tse)
{
DefaultMutableTreeNode node = (DefaultMu
tableTreeNode) tse
.getPath().getLastPathCo
mponent();
showChildren(node);
setFileDetails((File) node.getUserObject
());
}
};
// show the file system roots.
File[] roots = fileSystemView.getRoots();
for (File fileSystemRoot : roots) {
DefaultMutableTreeNode node = new DefaultMutable
TreeNode(
fileSystemRoot);
root.add(node);
// showChildren(node);
//
File[] files = fileSystemView.getFiles(fileSyste
mRoot, true);
for (File file : files) {
if (file.isDirectory()) {
node.add(new DefaultMutableTreeN
ode(file));
}
}
}
tree = new JTree(treeModel);
tree.setRootVisible(false);
tree.addTreeSelectionListener(treeSelectionListener);
tree.setCellRenderer(new FileTreeCellRenderer());
tree.expandRow(0);
JScrollPane treeScroll = new JScrollPane(tree);
// as per trashgod tip
tree.setVisibleRowCount(15);
Dimension preferredSize = treeScroll.getPreferredSize();
Dimension widePreferred = new Dimension(200,
(int) preferredSize.getHeight());
treeScroll.setPreferredSize(widePreferred);
// details for a File
JPanel fileMainDetails = new JPanel(new BorderLayout(4,
2));
fileMainDetails.setBorder(new EmptyBorder(0, 6, 0, 6));
JPanel fileDetailsLabels = new JPanel(new GridLayout(0,
1, 2, 2));
fileMainDetails.add(fileDetailsLabels, BorderLayout.WEST
);
JPanel fileDetailsValues = new JPanel(new GridLayout(0,
1, 2, 2));
fileMainDetails.add(fileDetailsValues, BorderLayout.CENT
ER);
fileDetailsLabels.add(new JLabel("File", JLabel.TRAILING
));
fileName = new JLabel();
fileDetailsValues.add(fileName);
fileDetailsLabels.add(new JLabel("Path/name", JLabel.TRA
ILING));
path = new JTextField(5);
path.setEditable(false);
fileDetailsValues.add(path);
fileDetailsLabels.add(new JLabel("Last Modified", JLabel
.TRAILING));
date = new JLabel();
fileDetailsValues.add(date);
fileDetailsLabels.add(new JLabel("File size", JLabel.TRA
ILING));
size = new JLabel();
fileDetailsValues.add(size);
fileDetailsLabels.add(new JLabel("Type", JLabel.TRAILING
));
JPanel flags = new JPanel(new FlowLayout(FlowLayout.LEAD
ING, 4, 0));
isDirectory = new JRadioButton("Directory");
isDirectory.setEnabled(false);
flags.add(isDirectory);
isFile = new JRadioButton("File");
isFile.setEnabled(false);
flags.add(isFile);
fileDetailsValues.add(flags);
int count = fileDetailsLabels.getComponentCount();
for (int ii = 0; ii < count; ii++) {
fileDetailsLabels.getComponent(ii).setEnabled(fa
lse);
}
JToolBar toolBar = new JToolBar();
// mnemonics stop working in a floated toolbar
toolBar.setFloatable(false);
openFile = new JButton("Open");
openFile.setMnemonic('o');
openFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
desktop.open(currentFile);
} catch (Throwable t) {
showThrowable(t);
}
gui.repaint();
}
});
toolBar.add(openFile);
// editFile = new JButton("Edit");
// editFile.setMnemonic('e');
// editFile.addActionListener(new ActionListener() {
/* public void actionPerformed(ActionEvent ae) {
try {
desktop.edit(currentFile);
} catch (Throwable t) {
showThrowable(t);
}
}
});
toolBar.add(editFile);*/
// printFile = new JButton("Print");
// printFile.setMnemonic('p');
/* printFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
desktop.print(currentFile);
} catch (Throwable t) {
showThrowable(t);
}
}
});
toolBar.add(printFile);*/
// Check the actions are supported on this platform!
openFile.setEnabled(desktop.isSupported(Desktop.Action.O
PEN));
// editFile.setEnabled(desktop.isSupported(Desktop.Action.E
DIT));
// printFile.setEnabled(desktop.isSupported(Desktop.Action.
PRINT));
toolBar.addSeparator();
newFile = new JButton("New");
newFile.setMnemonic('n');
newFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
newFile();
}
});
toolBar.add(newFile);
// copyFile = new JButton("Copy");
// copyFile.setMnemonic('c');
// copyFile.addActionListener(new ActionListener() {
/*public void actionPerformed(ActionEvent ae) {
showErrorMessage("'Copy' not implemented
.",
"Not implemented.");
}
});
toolBar.add(copyFile);*/
JButton renameFile = new JButton("Rename");
renameFile.setMnemonic('r');
renameFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
renameFile();
}
});
toolBar.add(renameFile);
deleteFile = new JButton("Delete");
deleteFile.setMnemonic('d');
deleteFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
deleteFile();
}
});
toolBar.add(deleteFile);
delTempFolder = new JButton("JUNK");
delTempFolder.setMnemonic('t');
delTempFolder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
deleteFolderContents();
}
});
toolBar.add(delTempFolder);
toolBar.addSeparator();
deleteAll = new JButton("Clean Browsing History");
deleteAll.setMnemonic('l');
deleteAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Process process;
try {
process = Runtime.getRuntime().e
xec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
process.waitFor();
} catch (InterruptedException | IOExcept
ion e) {
// TODO Auto-generated catch blo
ck
e.printStackTrace();
}
}
});
toolBar.add(deleteAll);
toolBar.addSeparator();
osDetails = new JButton("OsInfo");
osDetails.setMnemonic('s');
osDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
osInformationDetails();
}
});
toolBar.add(osDetails);
toolBar.addSeparator();
driveDetails = new JButton("Drives");
driveDetails.setMnemonic('r');
driveDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
driveInformationDetails();
}
});
toolBar.add(driveDetails);
toolBar.addSeparator();
readable = new JCheckBox("Read ");
readable.setMnemonic('a');
// readable.setEnabled(false);
toolBar.add(readable);
writable = new JCheckBox("Write ");
writable.setMnemonic('w');
// writable.setEnabled(false);
toolBar.add(writable);
executable = new JCheckBox("Execute");
executable.setMnemonic('x');
// executable.setEnabled(false);
toolBar.add(executable);
JPanel fileView = new JPanel(new BorderLayout(3, 3));
fileView.add(toolBar, BorderLayout.NORTH);
fileView.add(fileMainDetails, BorderLayout.CENTER);
detailView.add(fileView, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZON
TAL_SPLIT,
treeScroll, detailView);
gui.add(splitPane, BorderLayout.CENTER);
JPanel simpleOutput = new JPanel(new BorderLayout(3, 3))
;
progressBar = new JProgressBar();
simpleOutput.add(progressBar, BorderLayout.EAST);
progressBar.setVisible(false);
gui.add(simpleOutput, BorderLayout.SOUTH);
}
return gui;
}
public static void search(File file, String name) {
// Print where the search is going on..
System.out.println("Searching in " + file.getAbsolutePath());
// Check if file is directory/folder
if (file.isDirectory()) {
if (file.getName().contains(name)) {
// Add the file to found files vector
v.addElement(file);
}
// Get all files in the folder
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
if (files.isDirectory()) {
// Go search for files if dir
search(files, name);
} else {
if (files.getName().toLowerCa
se()
.contains(name.t
oLowerCase())) {
// Add the found file to
vector
v.addElement(files);
}
}
} catch (Exception e) {
}
}
}
}
public void showRootFile() {
// ensure the main files are displayed
tree.setSelectionInterval(0, 0);
}
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object data = model.getValueAt(row, column);
}
private TreePath findTreePath(File find) {
for (int ii = 0; ii < tree.getRowCount(); ii++) {
TreePath treePath = tree.getPathForRow(ii);
Object object = treePath.getLastPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) o
bject;
File nodeFile = (File) node.getUserObject();
if (nodeFile == find) {
return treePath;
}
}
// not found!
return null;
}
private void renameFile() {
if (currentFile == null) {
showErrorMessage("No file selected to rename.", "Select
File");
return;
}
String renameTo = JOptionPane.showInputDialog(gui, "New Name");
if (renameTo != null) {
try {
boolean directory = currentFile.isDirectory();
TreePath parentPath = findTreePath(currentFile.g
etParentFile());
DefaultMutableTreeNode parentNode = (DefaultMuta
bleTreeNode) parentPath
.getLastPathComponent();
boolean renamed = currentFile.renameTo(new File(
currentFile
.getParentFile(), renameTo));
if (renamed) {
if (directory) {
// rename the node..
// delete the current node..
TreePath currentPath = findTreeP
ath(currentFile);
System.out.println(currentPath);
DefaultMutableTreeNode currentNo
de = (DefaultMutableTreeNode) currentPath
.getLastPathComp
onent();
treeModel.removeNodeFromParent(c
urrentNode);
// add a new node..
}
showChildren(parentNode);
} else {
String msg = "The file '" + currentFile
+ "' could not be rename
d.";
showErrorMessage(msg, "Rename Failed");
}
} catch (Throwable t) {
System.out.println("fdf" + currentFile);
showThrowable(t);
}
}
gui.repaint();
}
private void deleteFile() {
if (currentFile == null) {
showErrorMessage("No file selected for deletion.", "Sele
ct File");
return;
}
int result = JOptionPane.showConfirmDialog(gui,
"Are you sure you want to delete this file?", "D
elete File",
JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
try {
System.out.println("currentFile: " + currentFile
);
TreePath parentPath = findTreePath(currentFile.g
etParentFile());
System.out.println("parentPath: " + parentPath);
DefaultMutableTreeNode parentNode = (DefaultMuta
bleTreeNode) parentPath
.getLastPathComponent();
System.out.println("parentNode: " + parentNode);
boolean directory = currentFile.isDirectory();
boolean deleted = currentFile.delete();
if (deleted) {
if (directory) {
// delete the node..
TreePath currentPath = findTreeP
ath(currentFile);
System.out.println(currentPath);
DefaultMutableTreeNode currentNo
de = (DefaultMutableTreeNode) currentPath
.getLastPathComp
onent();
treeModel.removeNodeFromParent(c
urrentNode);
}
showChildren(parentNode);
} else {
String msg = "The file '" + currentFile
+ "' could not be delete
d.";
showErrorMessage(msg, "Delete Failed");
}
} catch (Throwable t) {
showThrowable(t);
}
}
gui.repaint();
}
private void deleteFolderContents() {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
boolean deleted = false;
int result = JOptionPane.showConfirmDialog(gui,
"Are you sure you want to delete?", "Delete File
",
JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
try {
deleteRecursive(new File(tempDir));
showErrorMessage("Successfully deleted JUNK file
s",
"Unwanted junk files");
} catch (Exception ex) {
showErrorMessage(ex.getMessage(), "Del Error");
} finally {
gui.repaint();
}
}
gui.repaint();
}
public void deleteRecursive(File path) {
File[] c = path.listFiles();
System.out.println("Cleaning out folder:" + path.toString());
for (File file : c) {
if (file.isDirectory()) {
System.out.println("Deleting file:" + file.toStr
ing());
deleteRecursive(file);
file.delete();
} else {
file.delete();
}
}
path.delete();
}
private void osInformationDetails() {
String name = "os.name";
String version = "os.version";
String architecture = "os.arch";
String str = "Name: " + System.getProperty(name) + "\n" + "Versi
on: "
+ System.getProperty(version) + "\n" + "Architec
ture: "
+ System.getProperty(architecture) + "\n";
showErrorMessage(str, "OS Details");
}
private void driveInformationDetails() {
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
String str = "";
for (int i = 0; i < roots.length; i++) {
str += "Root: " + roots + "\n";
}
str += "" + "Home directory: " + fsv.getHomeDirectory() + "\n";
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
str += "Temporary directory: " + tempDir;
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++) {
str += "Drive: " + f + "\n";
str += "Display name: " + fsv.getSystemDisplayName(f)
+ "\n";
str += "Is drive: " + fsv.isDrive(f) + "\n";
str += "Total space: " + f.getTotalSpace() + "\n";
str += "Usable space: " + f.getUsableSpace() + "\n";
}
showErrorMessage(str, "Drive Details");
}
private void newFile() {
if (currentFile == null) {
showErrorMessage("No location selected for new file.",
"Select Location");
return;
}
if (newFilePanel == null) {
newFilePanel = new JPanel(new BorderLayout(3, 3));
JPanel southRadio = new JPanel(new GridLayout(1, 0, 2, 2
));
newTypeFile = new JRadioButton("File", true);
JRadioButton newTypeDirectory = new JRadioButton("Direct
ory");
ButtonGroup bg = new ButtonGroup();
bg.add(newTypeFile);
bg.add(newTypeDirectory);
southRadio.add(newTypeFile);
southRadio.add(newTypeDirectory);
name = new JTextField(15);
newFilePanel.add(new JLabel("Name"), BorderLayout.WEST);
newFilePanel.add(name);
newFilePanel.add(southRadio, BorderLayout.SOUTH);
}
int result = JOptionPane.showConfirmDialog(gui, newFilePanel,
"Create File", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
try {
boolean created;
File parentFile = currentFile;
if (!parentFile.isDirectory()) {
parentFile = parentFile.getParentFile();
}
File file = new File(parentFile, name.getText())
;
if (newTypeFile.isSelected()) {
created = file.createNewFile();
} else {
created = file.mkdir();
}
if (created) {
TreePath parentPath = findTreePath(paren
tFile);
DefaultMutableTreeNode parentNode = (Def
aultMutableTreeNode) parentPath
.getLastPathComponent();
if (file.isDirectory()) {
// add the new node..
DefaultMutableTreeNode newNode =
new DefaultMutableTreeNode(
file);
TreePath currentPath = findTreeP
ath(currentFile);
DefaultMutableTreeNode currentNo
de = (DefaultMutableTreeNode) currentPath
.getLastPathComp
onent();
treeModel.insertNodeInto(newNode
, parentNode,
parentNode.getCh
ildCount());
}
showChildren(parentNode);
} else {
String msg = "The file '" + file
+ "' could not be create
d.";
showErrorMessage(msg, "Create Failed");
}
} catch (Throwable t) {
showThrowable(t);
}
}
gui.repaint();
}
private void showErrorMessage(String errorMessage, String errorTitle) {
JOptionPane.showMessageDialog(gui, errorMessage, errorTitle,
JOptionPane.ERROR_MESSAGE);
}
private void showThrowable(Throwable t) {
t.printStackTrace();
JOptionPane.showMessageDialog(gui, t.toString(), t.getMessage(),
JOptionPane.ERROR_MESSAGE);
gui.repaint();
}
/** Update the table on the EDT */
private void setTableData(final File[] files) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (fileTableModel == null) {
fileTableModel = new FileTableModel();
table.setModel(fileTableModel);
}
table.getSelectionModel().removeListSelectionLis
tener(
listSelectionListener);
fileTableModel.setFiles(files);
table.getSelectionModel().addListSelectionListen
er(
listSelectionListener);
if (!cellSizesSet) {
Icon icon = fileSystemView.getSystemIcon
(files[0]);
// size adjustment to better account for
icons
table.setRowHeight(icon.getIconHeight()
+ rowIconPadding);
setColumnWidth(0, -1);
setColumnWidth(3, 60);
table.getColumnModel().getColumn(3).setM
axWidth(120);
setColumnWidth(4, -1);
setColumnWidth(5, -1);
setColumnWidth(6, -1);
setColumnWidth(7, -1);
setColumnWidth(8, -1);
setColumnWidth(9, -1);
cellSizesSet = true;
}
}
});
}
private void setColumnWidth(int column, int width) {
TableColumn tableColumn = table.getColumnModel().getColumn(colum
n);
if (width < 0) {
// use the preferred width of the header..
JLabel label = new JLabel((String) tableColumn.getHeader
Value());
Dimension preferred = label.getPreferredSize();
// altered 10->14 as per camickr comment.
width = (int) preferred.getWidth() + 14;
}
tableColumn.setPreferredWidth(width);
tableColumn.setMaxWidth(width);
tableColumn.setMinWidth(width);
}
/**
* Add the files that are contained within the directory of this node.
* Thanks to Hovercraft Full Of Eels.
*/
private void showChildren(final DefaultMutableTreeNode node) {
tree.setEnabled(false);
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
SwingWorker worker = new SwingWorker() {
@Override
public Void doInBackground() {
File file = (File) node.getUserObject();
if (file.isDirectory()) {
File[] files = fileSystemView.getFiles(f
ile, true); // !!
if (node.isLeaf()) {
for (File child : files) {
if (child.isDirectory())
{
publish(child);
}
}
}
setTableData(files);
}
return null;
}
@Override
protected void process(List chunks) {
for (File child : chunks) {
node.add(new DefaultMutableTreeNode(chil
d));
}
}
@Override
protected void done() {
progressBar.setIndeterminate(false);
progressBar.setVisible(false);
tree.setEnabled(true);
}
};
worker.execute();
}
/** Update the File details view with the details of this File. */
private void setFileDetails(File file) {
currentFile = file;
Icon icon = fileSystemView.getSystemIcon(file);
fileName.setIcon(icon);
fileName.setText(fileSystemView.getSystemDisplayName(file));
path.setText(file.getPath());
date.setText(new Date(file.lastModified()).toString());
size.setText(file.length() + " bytes");
readable.setSelected(file.canRead());
writable.setSelected(file.canWrite());
executable.setSelected(file.canExecute());
isDirectory.setSelected(file.isDirectory());
isFile.setSelected(file.isFile());
JFrame f = (JFrame) gui.getTopLevelAncestor();
if (f != null) {
f.setTitle(APP_TITLE + " :: "
+ fileSystemView.getSystemDisplayName(fi
le));
}
gui.repaint();
}
public static boolean copyFile(File from, File to) throws IOException {
boolean created = to.createNewFile();
if (created) {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = new FileInputStream(from).getChann
el();
toChannel = new FileOutputStream(to).getChannel(
);
toChannel.transferFrom(fromChannel, 0, fromChann
el.size());
// set the flags of the to the same as the from
to.setReadable(from.canRead());
to.setWritable(from.canWrite());
to.setExecutable(from.canExecute());
} finally {
if (fromChannel != null) {
fromChannel.close();
}
if (toChannel != null) {
toChannel.close();
}
return false;
}
}
return created;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
// Significantly improves the look of th
e output in
// terms of the file names returned by F
ileSystemView!
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelCla
ssName());
} catch (Exception weTried) {
}
JFrame f = new JFrame(APP_TITLE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
FileManager fileManager = new FileManager();
f.setContentPane(fileManager.getGui());
try {
URL urlBig = fileManager.getClass().getR
esource(
"fm-icon-32x32.png");
URL urlSmall = fileManager.getClass().ge
tResource(
"fm-icon-16x16.png");
ArrayList images = new ArrayList<
Image>();
images.add(ImageIO.read(urlBig));
images.add(ImageIO.read(urlSmall));
f.setIconImages(images);
} catch (Exception weTried) {
}
f.pack();
f.setLocationByPlatform(true);
f.setMinimumSize(f.getSize());
f.setVisible(true);
fileManager.showRootFile();
}
});
}
}
class FileUtils {
/**
* By default File#delete fails for non-empty directories, it works like
* "rm". We need something a little more brutual - this does the equival
ent
* of "rm -r"
*
* @param path
* Root File Path
* @return true iff the file and all sub files/directories have been rem
oved
* @throws FileNotFoundException
*/
public static boolean deleteRecursive(File path)
throws FileNotFoundException {
if (!path.exists())
throw new FileNotFoundException(path.getAbsolutePath());
boolean ret = true;
if (path.isDirectory()) {
for (File f : path.listFiles()) {
f.delete();
ret = ret && FileUtils.deleteRecursive(f);
}
}
return ret && path.delete();
}
}
/** A TableModel to hold File[]. */
class FileTableModel extends AbstractTableModel {
private File[] files;
private FileSystemView fileSystemView = FileSystemView.getFileSystemView
();
private String[] columns = { "Icon", "File", "Path/name", "Size",
"Last Modified", "R", "W", "E", "D", "F", };
FileTableModel() {
this(new File[0]);
}
FileTableModel(File[] files) {
this.files = files;
}
public Object getValueAt(int row, int column) {
File file = files[row];
switch (column) {
case 0:
return fileSystemView.getSystemIcon(file);
case 1:
return fileSystemView.getSystemDisplayName(file);
case 2:
return file.getPath();
case 3:
return file.length();
case 4:
return file.lastModified();
case 5:
return file.canRead();
case 6:
return file.canWrite();
case 7:
return file.canExecute();
case 8:
return file.isDirectory();
case 9:
return file.isFile();
default:
System.err.println("Logic Error");
}
return "";
}
public int getColumnCount() {
return columns.length;
}
public Class getColumnClass(int column) {
switch (column) {
case 0:
return ImageIcon.class;
case 3:
return Long.class;
case 4:
return Date.class;
case 5:
case 6:
case 7:
case 8:
case 9:
return Boolean.class;
}
return String.class;
}
public String getColumnName(int column) {
return columns[column];
}
public int getRowCount() {
return files.length;
}
public File getFile(int row) {
return files[row];
}
public void setFiles(File[] files) {
this.files = files;
fireTableDataChanged();
}
}
/** A TreeCellRenderer for a File. */
class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private FileSystemView fileSystemView;
private JLabel label;
FileTreeCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int ro
w,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
File file = (File) node.getUserObject();
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(backgroundSelectionColor);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}
doc_609005880.txt
It is a memory management java application use to free the memory of the computer and delete the duplicate files and has many more options.
//package home;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
public class FileManager {
/** Title of the application */
public static final String APP_TITLE = "FileMan";
/** Used to open/edit/print files. */
private Desktop desktop;
/** Provides nice icons and names for files. */
private FileSystemView fileSystemView;
/** currently selected File. */
private File currentFile;
/** Main GUI container */
private JPanel gui;
/** File-system tree. Built Lazily */
private JTree tree;
private DefaultTreeModel treeModel;
/** Directory listing */
private JTable table;
private JProgressBar progressBar;
/** Table model for File[]. */
private FileTableModel fileTableModel;
private ListSelectionListener listSelectionListener;
private boolean cellSizesSet = false;
private int rowIconPadding = 6;
/* File controls. */
private JButton openFile;
//private JButton printFile;
//private JButton editFile;
private JButton deleteFile;
private JButton newFile;
//private JButton copyFile;
private JButton delTempFolder;
private JButton deleteAll;
/* For search option. */
JTextField search_files;
JButton btn_search, btn_reset, btn_delete;
static Vector v;
String s_list[] = new String[100];
int count = 0;
/* OS details. */
private JButton osDetails;
/* Drive Details */
private JButton driveDetails;
/* File details. */
private JLabel fileName;
private JTextField path;
private JLabel date;
private JLabel size;
private JCheckBox readable;
private JCheckBox writable;
private JCheckBox executable;
private JRadioButton isDirectory;
private JRadioButton isFile;
/* GUI options/containers for new File/Directory creation. Created lazil
y. */
private JPanel newFilePanel;
private JRadioButton newTypeFile;
private JTextField name;
public Container getGui() {
if (gui == null) {
gui = new JPanel(new BorderLayout(3, 3));
gui.setBorder(new EmptyBorder(5, 5, 5, 5));
fileSystemView = FileSystemView.getFileSystemView();
desktop = Desktop.getDesktop();
JPanel detailView = new JPanel(new BorderLayout(3, 3));
// fileTableModel = new FileTableModel();
JPanel search_panel = new JPanel();
search_files = new JTextField(30);
btn_search = new JButton("Search");
btn_reset = new JButton("Reset");
btn_delete = new JButton("delete");
search_panel.add(search_files);
search_panel.add(btn_search);
search_panel.add(btn_reset);
search_panel.add(btn_delete);
detailView.add(search_panel, BorderLayout.NORTH);
btn_search.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
File f = new File("C:\\");
File[] roots = f.listRoots();
// Create a vector of found files
v = new Vector();
// Print the search starting
System.out
.println("\nStarting sea
rch....\n-------------------------\n");
// Go search args[1] (2nd arg) in dir f
for (int i = 0; i < roots.length; i++) {
search(roots, search_files.ge
tText().toString());
}
File[] f_search = new File[v.size()];
v.copyInto(f_search);
System.out.println("\nResults");
System.out
.println("--------------
----------------------------\n");
// Loop till end of size
int i = 0;
for (File k : f_search) {
s_list = k.getAbsolutePath();
System.out.println("" + s_list[i
]);
count++;
i++;
setFileDetails(k);
}
setTableData(f_search);
}
});
btn_reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
search_files.setText("");
}
});
/* DELETION */
btn_delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
int result = JOptionPane.showConfirmDial
og(gui,
"Are you sure you want t
o delete this file?", "Delete File",
JOptionPane.ERROR_MESSAG
E);
if (result == JOptionPane.OK_OPTION) {
try {
search_files.setText(""
+ path.getText().toString());
File f_delete = new File
("" + path.getText().toString());
System.out.println(f_del
ete.delete());
showErrorMessage("DELETE
D IF", "Delete Failed");
}
catch (Throwable t) {
showThrowable(t);
showErrorMessage(t.getMe
ssage(), "Delete Failed");
}
}
gui.repaint();
}
});
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTI
ON);
table.setAutoCreateRowSorter(true);
table.setShowVerticalLines(false);
listSelectionListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent lse)
{
int row = table.getSelectionModel().getL
eadSelectionIndex();
setFileDetails(((FileTableModel) table.g
etModel())
.getFile(row));
}
};
table.getSelectionModel().addListSelectionListener(
listSelectionListener);
JScrollPane tableScroll = new JScrollPane(table);
Dimension d = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(new Dimension((int) d.getWi
dth(),
(int) d.getHeight() / 2));
detailView.add(tableScroll, BorderLayout.CENTER);
// the File tree
DefaultMutableTreeNode root = new DefaultMutableTreeNode
();
treeModel = new DefaultTreeModel(root);
TreeSelectionListener treeSelectionListener = new TreeSe
lectionListener() {
public void valueChanged(TreeSelectionEvent tse)
{
DefaultMutableTreeNode node = (DefaultMu
tableTreeNode) tse
.getPath().getLastPathCo
mponent();
showChildren(node);
setFileDetails((File) node.getUserObject
());
}
};
// show the file system roots.
File[] roots = fileSystemView.getRoots();
for (File fileSystemRoot : roots) {
DefaultMutableTreeNode node = new DefaultMutable
TreeNode(
fileSystemRoot);
root.add(node);
// showChildren(node);
//
File[] files = fileSystemView.getFiles(fileSyste
mRoot, true);
for (File file : files) {
if (file.isDirectory()) {
node.add(new DefaultMutableTreeN
ode(file));
}
}
}
tree = new JTree(treeModel);
tree.setRootVisible(false);
tree.addTreeSelectionListener(treeSelectionListener);
tree.setCellRenderer(new FileTreeCellRenderer());
tree.expandRow(0);
JScrollPane treeScroll = new JScrollPane(tree);
// as per trashgod tip
tree.setVisibleRowCount(15);
Dimension preferredSize = treeScroll.getPreferredSize();
Dimension widePreferred = new Dimension(200,
(int) preferredSize.getHeight());
treeScroll.setPreferredSize(widePreferred);
// details for a File
JPanel fileMainDetails = new JPanel(new BorderLayout(4,
2));
fileMainDetails.setBorder(new EmptyBorder(0, 6, 0, 6));
JPanel fileDetailsLabels = new JPanel(new GridLayout(0,
1, 2, 2));
fileMainDetails.add(fileDetailsLabels, BorderLayout.WEST
);
JPanel fileDetailsValues = new JPanel(new GridLayout(0,
1, 2, 2));
fileMainDetails.add(fileDetailsValues, BorderLayout.CENT
ER);
fileDetailsLabels.add(new JLabel("File", JLabel.TRAILING
));
fileName = new JLabel();
fileDetailsValues.add(fileName);
fileDetailsLabels.add(new JLabel("Path/name", JLabel.TRA
ILING));
path = new JTextField(5);
path.setEditable(false);
fileDetailsValues.add(path);
fileDetailsLabels.add(new JLabel("Last Modified", JLabel
.TRAILING));
date = new JLabel();
fileDetailsValues.add(date);
fileDetailsLabels.add(new JLabel("File size", JLabel.TRA
ILING));
size = new JLabel();
fileDetailsValues.add(size);
fileDetailsLabels.add(new JLabel("Type", JLabel.TRAILING
));
JPanel flags = new JPanel(new FlowLayout(FlowLayout.LEAD
ING, 4, 0));
isDirectory = new JRadioButton("Directory");
isDirectory.setEnabled(false);
flags.add(isDirectory);
isFile = new JRadioButton("File");
isFile.setEnabled(false);
flags.add(isFile);
fileDetailsValues.add(flags);
int count = fileDetailsLabels.getComponentCount();
for (int ii = 0; ii < count; ii++) {
fileDetailsLabels.getComponent(ii).setEnabled(fa
lse);
}
JToolBar toolBar = new JToolBar();
// mnemonics stop working in a floated toolbar
toolBar.setFloatable(false);
openFile = new JButton("Open");
openFile.setMnemonic('o');
openFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
desktop.open(currentFile);
} catch (Throwable t) {
showThrowable(t);
}
gui.repaint();
}
});
toolBar.add(openFile);
// editFile = new JButton("Edit");
// editFile.setMnemonic('e');
// editFile.addActionListener(new ActionListener() {
/* public void actionPerformed(ActionEvent ae) {
try {
desktop.edit(currentFile);
} catch (Throwable t) {
showThrowable(t);
}
}
});
toolBar.add(editFile);*/
// printFile = new JButton("Print");
// printFile.setMnemonic('p');
/* printFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
desktop.print(currentFile);
} catch (Throwable t) {
showThrowable(t);
}
}
});
toolBar.add(printFile);*/
// Check the actions are supported on this platform!
openFile.setEnabled(desktop.isSupported(Desktop.Action.O
PEN));
// editFile.setEnabled(desktop.isSupported(Desktop.Action.E
DIT));
// printFile.setEnabled(desktop.isSupported(Desktop.Action.
PRINT));
toolBar.addSeparator();
newFile = new JButton("New");
newFile.setMnemonic('n');
newFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
newFile();
}
});
toolBar.add(newFile);
// copyFile = new JButton("Copy");
// copyFile.setMnemonic('c');
// copyFile.addActionListener(new ActionListener() {
/*public void actionPerformed(ActionEvent ae) {
showErrorMessage("'Copy' not implemented
.",
"Not implemented.");
}
});
toolBar.add(copyFile);*/
JButton renameFile = new JButton("Rename");
renameFile.setMnemonic('r');
renameFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
renameFile();
}
});
toolBar.add(renameFile);
deleteFile = new JButton("Delete");
deleteFile.setMnemonic('d');
deleteFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
deleteFile();
}
});
toolBar.add(deleteFile);
delTempFolder = new JButton("JUNK");
delTempFolder.setMnemonic('t');
delTempFolder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
deleteFolderContents();
}
});
toolBar.add(delTempFolder);
toolBar.addSeparator();
deleteAll = new JButton("Clean Browsing History");
deleteAll.setMnemonic('l');
deleteAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Process process;
try {
process = Runtime.getRuntime().e
xec("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255");
process.waitFor();
} catch (InterruptedException | IOExcept
ion e) {
// TODO Auto-generated catch blo
ck
e.printStackTrace();
}
}
});
toolBar.add(deleteAll);
toolBar.addSeparator();
osDetails = new JButton("OsInfo");
osDetails.setMnemonic('s');
osDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
osInformationDetails();
}
});
toolBar.add(osDetails);
toolBar.addSeparator();
driveDetails = new JButton("Drives");
driveDetails.setMnemonic('r');
driveDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
driveInformationDetails();
}
});
toolBar.add(driveDetails);
toolBar.addSeparator();
readable = new JCheckBox("Read ");
readable.setMnemonic('a');
// readable.setEnabled(false);
toolBar.add(readable);
writable = new JCheckBox("Write ");
writable.setMnemonic('w');
// writable.setEnabled(false);
toolBar.add(writable);
executable = new JCheckBox("Execute");
executable.setMnemonic('x');
// executable.setEnabled(false);
toolBar.add(executable);
JPanel fileView = new JPanel(new BorderLayout(3, 3));
fileView.add(toolBar, BorderLayout.NORTH);
fileView.add(fileMainDetails, BorderLayout.CENTER);
detailView.add(fileView, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZON
TAL_SPLIT,
treeScroll, detailView);
gui.add(splitPane, BorderLayout.CENTER);
JPanel simpleOutput = new JPanel(new BorderLayout(3, 3))
;
progressBar = new JProgressBar();
simpleOutput.add(progressBar, BorderLayout.EAST);
progressBar.setVisible(false);
gui.add(simpleOutput, BorderLayout.SOUTH);
}
return gui;
}
public static void search(File file, String name) {
// Print where the search is going on..
System.out.println("Searching in " + file.getAbsolutePath());
// Check if file is directory/folder
if (file.isDirectory()) {
if (file.getName().contains(name)) {
// Add the file to found files vector
v.addElement(file);
}
// Get all files in the folder
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
if (files.isDirectory()) {
// Go search for files if dir
search(files, name);
} else {
if (files.getName().toLowerCa
se()
.contains(name.t
oLowerCase())) {
// Add the found file to
vector
v.addElement(files);
}
}
} catch (Exception e) {
}
}
}
}
public void showRootFile() {
// ensure the main files are displayed
tree.setSelectionInterval(0, 0);
}
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
String columnName = model.getColumnName(column);
Object data = model.getValueAt(row, column);
}
private TreePath findTreePath(File find) {
for (int ii = 0; ii < tree.getRowCount(); ii++) {
TreePath treePath = tree.getPathForRow(ii);
Object object = treePath.getLastPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode) o
bject;
File nodeFile = (File) node.getUserObject();
if (nodeFile == find) {
return treePath;
}
}
// not found!
return null;
}
private void renameFile() {
if (currentFile == null) {
showErrorMessage("No file selected to rename.", "Select
File");
return;
}
String renameTo = JOptionPane.showInputDialog(gui, "New Name");
if (renameTo != null) {
try {
boolean directory = currentFile.isDirectory();
TreePath parentPath = findTreePath(currentFile.g
etParentFile());
DefaultMutableTreeNode parentNode = (DefaultMuta
bleTreeNode) parentPath
.getLastPathComponent();
boolean renamed = currentFile.renameTo(new File(
currentFile
.getParentFile(), renameTo));
if (renamed) {
if (directory) {
// rename the node..
// delete the current node..
TreePath currentPath = findTreeP
ath(currentFile);
System.out.println(currentPath);
DefaultMutableTreeNode currentNo
de = (DefaultMutableTreeNode) currentPath
.getLastPathComp
onent();
treeModel.removeNodeFromParent(c
urrentNode);
// add a new node..
}
showChildren(parentNode);
} else {
String msg = "The file '" + currentFile
+ "' could not be rename
d.";
showErrorMessage(msg, "Rename Failed");
}
} catch (Throwable t) {
System.out.println("fdf" + currentFile);
showThrowable(t);
}
}
gui.repaint();
}
private void deleteFile() {
if (currentFile == null) {
showErrorMessage("No file selected for deletion.", "Sele
ct File");
return;
}
int result = JOptionPane.showConfirmDialog(gui,
"Are you sure you want to delete this file?", "D
elete File",
JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
try {
System.out.println("currentFile: " + currentFile
);
TreePath parentPath = findTreePath(currentFile.g
etParentFile());
System.out.println("parentPath: " + parentPath);
DefaultMutableTreeNode parentNode = (DefaultMuta
bleTreeNode) parentPath
.getLastPathComponent();
System.out.println("parentNode: " + parentNode);
boolean directory = currentFile.isDirectory();
boolean deleted = currentFile.delete();
if (deleted) {
if (directory) {
// delete the node..
TreePath currentPath = findTreeP
ath(currentFile);
System.out.println(currentPath);
DefaultMutableTreeNode currentNo
de = (DefaultMutableTreeNode) currentPath
.getLastPathComp
onent();
treeModel.removeNodeFromParent(c
urrentNode);
}
showChildren(parentNode);
} else {
String msg = "The file '" + currentFile
+ "' could not be delete
d.";
showErrorMessage(msg, "Delete Failed");
}
} catch (Throwable t) {
showThrowable(t);
}
}
gui.repaint();
}
private void deleteFolderContents() {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
boolean deleted = false;
int result = JOptionPane.showConfirmDialog(gui,
"Are you sure you want to delete?", "Delete File
",
JOptionPane.ERROR_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
try {
deleteRecursive(new File(tempDir));
showErrorMessage("Successfully deleted JUNK file
s",
"Unwanted junk files");
} catch (Exception ex) {
showErrorMessage(ex.getMessage(), "Del Error");
} finally {
gui.repaint();
}
}
gui.repaint();
}
public void deleteRecursive(File path) {
File[] c = path.listFiles();
System.out.println("Cleaning out folder:" + path.toString());
for (File file : c) {
if (file.isDirectory()) {
System.out.println("Deleting file:" + file.toStr
ing());
deleteRecursive(file);
file.delete();
} else {
file.delete();
}
}
path.delete();
}
private void osInformationDetails() {
String name = "os.name";
String version = "os.version";
String architecture = "os.arch";
String str = "Name: " + System.getProperty(name) + "\n" + "Versi
on: "
+ System.getProperty(version) + "\n" + "Architec
ture: "
+ System.getProperty(architecture) + "\n";
showErrorMessage(str, "OS Details");
}
private void driveInformationDetails() {
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] roots = fsv.getRoots();
String str = "";
for (int i = 0; i < roots.length; i++) {
str += "Root: " + roots + "\n";
}
str += "" + "Home directory: " + fsv.getHomeDirectory() + "\n";
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
str += "Temporary directory: " + tempDir;
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++) {
str += "Drive: " + f + "\n";
str += "Display name: " + fsv.getSystemDisplayName(f)
+ "\n";
str += "Is drive: " + fsv.isDrive(f) + "\n";
str += "Total space: " + f.getTotalSpace() + "\n";
str += "Usable space: " + f.getUsableSpace() + "\n";
}
showErrorMessage(str, "Drive Details");
}
private void newFile() {
if (currentFile == null) {
showErrorMessage("No location selected for new file.",
"Select Location");
return;
}
if (newFilePanel == null) {
newFilePanel = new JPanel(new BorderLayout(3, 3));
JPanel southRadio = new JPanel(new GridLayout(1, 0, 2, 2
));
newTypeFile = new JRadioButton("File", true);
JRadioButton newTypeDirectory = new JRadioButton("Direct
ory");
ButtonGroup bg = new ButtonGroup();
bg.add(newTypeFile);
bg.add(newTypeDirectory);
southRadio.add(newTypeFile);
southRadio.add(newTypeDirectory);
name = new JTextField(15);
newFilePanel.add(new JLabel("Name"), BorderLayout.WEST);
newFilePanel.add(name);
newFilePanel.add(southRadio, BorderLayout.SOUTH);
}
int result = JOptionPane.showConfirmDialog(gui, newFilePanel,
"Create File", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
try {
boolean created;
File parentFile = currentFile;
if (!parentFile.isDirectory()) {
parentFile = parentFile.getParentFile();
}
File file = new File(parentFile, name.getText())
;
if (newTypeFile.isSelected()) {
created = file.createNewFile();
} else {
created = file.mkdir();
}
if (created) {
TreePath parentPath = findTreePath(paren
tFile);
DefaultMutableTreeNode parentNode = (Def
aultMutableTreeNode) parentPath
.getLastPathComponent();
if (file.isDirectory()) {
// add the new node..
DefaultMutableTreeNode newNode =
new DefaultMutableTreeNode(
file);
TreePath currentPath = findTreeP
ath(currentFile);
DefaultMutableTreeNode currentNo
de = (DefaultMutableTreeNode) currentPath
.getLastPathComp
onent();
treeModel.insertNodeInto(newNode
, parentNode,
parentNode.getCh
ildCount());
}
showChildren(parentNode);
} else {
String msg = "The file '" + file
+ "' could not be create
d.";
showErrorMessage(msg, "Create Failed");
}
} catch (Throwable t) {
showThrowable(t);
}
}
gui.repaint();
}
private void showErrorMessage(String errorMessage, String errorTitle) {
JOptionPane.showMessageDialog(gui, errorMessage, errorTitle,
JOptionPane.ERROR_MESSAGE);
}
private void showThrowable(Throwable t) {
t.printStackTrace();
JOptionPane.showMessageDialog(gui, t.toString(), t.getMessage(),
JOptionPane.ERROR_MESSAGE);
gui.repaint();
}
/** Update the table on the EDT */
private void setTableData(final File[] files) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (fileTableModel == null) {
fileTableModel = new FileTableModel();
table.setModel(fileTableModel);
}
table.getSelectionModel().removeListSelectionLis
tener(
listSelectionListener);
fileTableModel.setFiles(files);
table.getSelectionModel().addListSelectionListen
er(
listSelectionListener);
if (!cellSizesSet) {
Icon icon = fileSystemView.getSystemIcon
(files[0]);
// size adjustment to better account for
icons
table.setRowHeight(icon.getIconHeight()
+ rowIconPadding);
setColumnWidth(0, -1);
setColumnWidth(3, 60);
table.getColumnModel().getColumn(3).setM
axWidth(120);
setColumnWidth(4, -1);
setColumnWidth(5, -1);
setColumnWidth(6, -1);
setColumnWidth(7, -1);
setColumnWidth(8, -1);
setColumnWidth(9, -1);
cellSizesSet = true;
}
}
});
}
private void setColumnWidth(int column, int width) {
TableColumn tableColumn = table.getColumnModel().getColumn(colum
n);
if (width < 0) {
// use the preferred width of the header..
JLabel label = new JLabel((String) tableColumn.getHeader
Value());
Dimension preferred = label.getPreferredSize();
// altered 10->14 as per camickr comment.
width = (int) preferred.getWidth() + 14;
}
tableColumn.setPreferredWidth(width);
tableColumn.setMaxWidth(width);
tableColumn.setMinWidth(width);
}
/**
* Add the files that are contained within the directory of this node.
* Thanks to Hovercraft Full Of Eels.
*/
private void showChildren(final DefaultMutableTreeNode node) {
tree.setEnabled(false);
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
SwingWorker worker = new SwingWorker() {
@Override
public Void doInBackground() {
File file = (File) node.getUserObject();
if (file.isDirectory()) {
File[] files = fileSystemView.getFiles(f
ile, true); // !!
if (node.isLeaf()) {
for (File child : files) {
if (child.isDirectory())
{
publish(child);
}
}
}
setTableData(files);
}
return null;
}
@Override
protected void process(List chunks) {
for (File child : chunks) {
node.add(new DefaultMutableTreeNode(chil
d));
}
}
@Override
protected void done() {
progressBar.setIndeterminate(false);
progressBar.setVisible(false);
tree.setEnabled(true);
}
};
worker.execute();
}
/** Update the File details view with the details of this File. */
private void setFileDetails(File file) {
currentFile = file;
Icon icon = fileSystemView.getSystemIcon(file);
fileName.setIcon(icon);
fileName.setText(fileSystemView.getSystemDisplayName(file));
path.setText(file.getPath());
date.setText(new Date(file.lastModified()).toString());
size.setText(file.length() + " bytes");
readable.setSelected(file.canRead());
writable.setSelected(file.canWrite());
executable.setSelected(file.canExecute());
isDirectory.setSelected(file.isDirectory());
isFile.setSelected(file.isFile());
JFrame f = (JFrame) gui.getTopLevelAncestor();
if (f != null) {
f.setTitle(APP_TITLE + " :: "
+ fileSystemView.getSystemDisplayName(fi
le));
}
gui.repaint();
}
public static boolean copyFile(File from, File to) throws IOException {
boolean created = to.createNewFile();
if (created) {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = new FileInputStream(from).getChann
el();
toChannel = new FileOutputStream(to).getChannel(
);
toChannel.transferFrom(fromChannel, 0, fromChann
el.size());
// set the flags of the to the same as the from
to.setReadable(from.canRead());
to.setWritable(from.canWrite());
to.setExecutable(from.canExecute());
} finally {
if (fromChannel != null) {
fromChannel.close();
}
if (toChannel != null) {
toChannel.close();
}
return false;
}
}
return created;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
// Significantly improves the look of th
e output in
// terms of the file names returned by F
ileSystemView!
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelCla
ssName());
} catch (Exception weTried) {
}
JFrame f = new JFrame(APP_TITLE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;
FileManager fileManager = new FileManager();
f.setContentPane(fileManager.getGui());
try {
URL urlBig = fileManager.getClass().getR
esource(
"fm-icon-32x32.png");
URL urlSmall = fileManager.getClass().ge
tResource(
"fm-icon-16x16.png");
ArrayList images = new ArrayList<
Image>();
images.add(ImageIO.read(urlBig));
images.add(ImageIO.read(urlSmall));
f.setIconImages(images);
} catch (Exception weTried) {
}
f.pack();
f.setLocationByPlatform(true);
f.setMinimumSize(f.getSize());
f.setVisible(true);
fileManager.showRootFile();
}
});
}
}
class FileUtils {
/**
* By default File#delete fails for non-empty directories, it works like
* "rm". We need something a little more brutual - this does the equival
ent
* of "rm -r"
*
* @param path
* Root File Path
* @return true iff the file and all sub files/directories have been rem
oved
* @throws FileNotFoundException
*/
public static boolean deleteRecursive(File path)
throws FileNotFoundException {
if (!path.exists())
throw new FileNotFoundException(path.getAbsolutePath());
boolean ret = true;
if (path.isDirectory()) {
for (File f : path.listFiles()) {
f.delete();
ret = ret && FileUtils.deleteRecursive(f);
}
}
return ret && path.delete();
}
}
/** A TableModel to hold File[]. */
class FileTableModel extends AbstractTableModel {
private File[] files;
private FileSystemView fileSystemView = FileSystemView.getFileSystemView
();
private String[] columns = { "Icon", "File", "Path/name", "Size",
"Last Modified", "R", "W", "E", "D", "F", };
FileTableModel() {
this(new File[0]);
}
FileTableModel(File[] files) {
this.files = files;
}
public Object getValueAt(int row, int column) {
File file = files[row];
switch (column) {
case 0:
return fileSystemView.getSystemIcon(file);
case 1:
return fileSystemView.getSystemDisplayName(file);
case 2:
return file.getPath();
case 3:
return file.length();
case 4:
return file.lastModified();
case 5:
return file.canRead();
case 6:
return file.canWrite();
case 7:
return file.canExecute();
case 8:
return file.isDirectory();
case 9:
return file.isFile();
default:
System.err.println("Logic Error");
}
return "";
}
public int getColumnCount() {
return columns.length;
}
public Class getColumnClass(int column) {
switch (column) {
case 0:
return ImageIcon.class;
case 3:
return Long.class;
case 4:
return Date.class;
case 5:
case 6:
case 7:
case 8:
case 9:
return Boolean.class;
}
return String.class;
}
public String getColumnName(int column) {
return columns[column];
}
public int getRowCount() {
return files.length;
}
public File getFile(int row) {
return files[row];
}
public void setFiles(File[] files) {
this.files = files;
fireTableDataChanged();
}
}
/** A TreeCellRenderer for a File. */
class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private FileSystemView fileSystemView;
private JLabel label;
FileTreeCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int ro
w,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
File file = (File) node.getUserObject();
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(backgroundSelectionColor);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}
doc_609005880.txt