Java实现读取某个路径下的文件目录
比如D:/ABC/文件夹下,有10个文件,我娶的这10个文件的名字,
取得名字后,我想访问哪个就访问那个啦。
当然,如果能做到向Windos打开文件目录那样更好了,但是我的文件保存在服务器上面,我只要知道服务器那个文件夹里的所有文件名,另外用程序去实现读取这个文件吧。 展开
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.FileFilter;
import java.util.Calendar;
import java.util.ArrayList;
import java.text.SimpleDateFormat;
import java.text.MessageFormat;
/**
* @author Hardneedl
*/
class JavaExplorer extends JFrame {
private static final Dimension minSize = new Dimension(300, 200);
private static final Dimension maxSize = new Dimension(1024, 768);
private static final Dimension preferredSize = new Dimension(600, 400);
private JLabel statusLabel;
private JTree tree;
private JTable detailTable;
private FileTableModel tableModel;
public Dimension getMaximumSize() {return maxSize;}
public Dimension getMinimumSize() {return minSize;}
public Dimension getPreferredSize() {return preferredSize;}
public String getTitle() {return "Java Explorer";}
JavaExplorer() throws HeadlessException {
init();
doLay();
attachListeners();
}
private void init() {
statusLabel = new JLabel(){public Color getForeground() {return Color.BLUE;}};
tree = new JTree(new FileTreeModel());
tree.setCellRenderer(new DirCellRenderer());
detailTable = new JTable(tableModel = new FileTableModel());
detailTable.getColumnModel().getColumn(2).setCellRenderer(new TableCellRenderer(){
private JLabel label=new JLabel();
private final SimpleDateFormat format = new SimpleDateFormat("yyyy年mm月dd日 HH时MM分ss秒");
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof Calendar){
Calendar cal = (Calendar)value;
label.setText( format.format(cal.getTime()) );
}
return label;
}
});
detailTable.getColumnModel().getColumn(0).setCellRenderer(new TableCellRenderer(){
private JLabel label = new JLabel();
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value instanceof File) {
File f = (File)value;
label.setText(f.getName());
label.setForeground( f.isDirectory()? Color.RED : Color.BLACK);
}
return label;
}
});
}
private void doLay() {
Container container = getContentPane();
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), new JScrollPane(detailTable));
container.add(splitPane,BorderLayout.CENTER);
container.add(statusLabel,BorderLayout.SOUTH);
pack();
}
private void attachListeners() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tree.addTreeSelectionListener(new SelectionListener());
tree.addTreeSelectionListener(new _DirSelectionListener());
DirCellSelectedListener ck =new DirCellSelectedListener(tree);
detailTable.addKeyListener(ck);
detailTable.addMouseListener(ck);
}
public static void main(String[] args) {
new JavaExplorer().setVisible(true);
}
private class FileTreeModel implements TreeModel {
static final String root = "我的电脑";
private File[] rootFiles;
private final FileFilter dirFilter = new FileFilter(){
public boolean accept(File f) {return f.isDirectory();}
};
private FileTreeModel() {rootFiles = File.listRoots();}
public Object getRoot() {return root;}
public Object getChild(Object parent, int index) {
if (parent==getRoot()) return rootFiles[index];
if (parent instanceof File) {
File pf = (File)parent;
return pf.listFiles(dirFilter)[index];
}
return null;
}
public int getChildCount(Object parent) {
if (parent == getRoot()) return rootFiles.length;
if (parent instanceof File){
File pf = (File)parent;
File[] fs = pf.listFiles(dirFilter);
return fs == null?0:fs.length;
}
return 0;
}
public boolean isLeaf(Object node) {return false;}
public void valueForPathChanged(TreePath path, Object newValue) {}
public void addTreeModelListener(TreeModelListener l) {}
public void removeTreeModelListener(TreeModelListener l) {}
public int getIndexOfChild(Object parent, Object child) {
if (parent == getRoot()) {
for (int i = 0,j=rootFiles.length; i < j; i++)
if (rootFiles[i]==child) return i;
}
if (parent instanceof File) {
File pf = (File)parent;
File[] fs = pf.listFiles(dirFilter);
for (int i = 0,j=fs.length; i < j; i++) {
if (fs[i].equals(child)) return i;
}
}
return -1;
}
}
private class FileTableModel extends AbstractTableModel {
public int getRowCount() {return dir==null||dir.isFile()?0:dir.listFiles().length;}
public int getColumnCount() {return 3;}
private File dir;
private void setDir(File dir){
this.dir = dir;
fireTableDataChanged();
}
public Class<?> getColumnClass(int columnIndex) {
switch(columnIndex) {
case 0:return File.class;
case 1:return Integer.class;
case 2:return Calendar.class;
default:return String.class;
}
}
public String getColumnName(int column) {
switch (column) {
case 0: return "名称";
case 1: return "大小";
case 2: return "修改日期";
default:return "";
}
}
public Object getValueAt(int rowIndex, int columnIndex) {
File[]fs=dir.listFiles();
File f = fs[rowIndex];
switch(columnIndex){
case 0:return f;
case 1:
if (f.isDirectory()) return null;
try {
if (f.canRead())
return new FileInputStream(f).available();
} catch (IOException e) {
e.printStackTrace();
}
case 2:
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(f.lastModified());
return cl;
}
return null;
}
}
private class _DirSelectionListener implements TreeSelectionListener {
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getNewLeadSelectionPath();
if (path!=null){
Object obj = path.getLastPathComponent();
if (obj instanceof File) {
File f = (File)obj;
File[] fs = f.listFiles();
statusLabel.setText(fs==null?null:MessageFormat.format("{0}个文件",fs.length ));
}
else
statusLabel.setText(null);
}
}
}
private class DirCellRenderer extends JLabel implements TreeCellRenderer {
public boolean isOpaque() {return true;}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (value instanceof File){
String s = ((File)value).getName();
setText(s.isEmpty()?value.toString() : s);
}
else
setText(value.toString());
setForeground(selected? Color.BLUE : Color.BLACK);
setBackground(selected? Color.YELLOW : Color.WHITE);
return this;
}
}
private class SelectionListener implements TreeSelectionListener{
public void valueChanged(TreeSelectionEvent e) {
Object obj = e.getNewLeadSelectionPath().getLastPathComponent();
if (obj instanceof File) {
tableModel.setDir((File)obj);
}
}
}
private class DirCellSelectedListener implements KeyListener, MouseListener {
private JTree tree;
private DirCellSelectedListener(JTree t) {tree=t;}
private void action(InputEvent e){
if (e instanceof MouseEvent) {
}
if (e instanceof KeyEvent) {
}
}
private void expand(File f){
if (f.isDirectory()) {
ArrayList<File> L = new ArrayList<File>();
L.add(f);
File parentFile = f.getParentFile();
while (parentFile != null) {
L.add(parentFile);
parentFile = parentFile.getParentFile();
}
TreePath treePath = new TreePath(FileTreeModel.root);
for (int i = L.size()-1; i > -1; i--) {
treePath = treePath.pathByAddingChild(L.get(i));
}
tree.setSelectionPath(treePath);
}
}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_ENTER) return;
if (e.getSource() == detailTable) {
int row = detailTable.getSelectedRow();
if (row!=-1){
File f = (File)detailTable.getValueAt(row,0);
expand(f);
}
}
}
public void keyReleased(KeyEvent e) {
}
public void mouseClicked(MouseEvent e) {
if (e.getClickCount()==2) {
if(e.getSource()==detailTable){
int row = detailTable.getSelectedRow();
if (row!=-1){
File f = (File)detailTable.getValueAt(row,0);
expand(f);
}
}
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
}