我想自己用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) {
}
}
}
本回答被提问者采纳java怎样获得某个目录下所有文件的文件名
import java.io.File;public class GetAllFiles { public static void main(String[] args) { \/\/路径 这里写一个路径进去 String path="F:\\\\QQ文档";\/\/调用方法 getFiles(path);} \/ 递归获取某路径下的所有文件,文件夹,并输出 \/ public static void getFiles(String path) { File file ...
Java中遍历目录下的文件方法
若路径存在,调用list()方法获取一个包含目录下所有文件文件名的String数组names。然后,通过循环遍历数组names,打印出每个文件的文件名,实现遍历目录内所有文件的功能。然而,若仅需获取指定类型的文件,如目录下所有".java"文件,File类提供重载的list(FilenameFilter filter)方法。此方法接收一个Filename...
java代码 读取一个文件夹下的所有文件夹及里面的文件。
我给你个例子,你把其中的路径File file = new File("c:\\\\tmp\\\\5");改成你的路径就行了。public class Test2 { public static void main(String[] args){ File file = new File("c:\\\\tmp\\\\5");Test2 t = new Test2();t.method(file);} public void method(File f){ File[] F...
java怎样获得某个目录下所有文件的文件名
如下代码使用递归算法遍历某个目录下的所有文件,并输出文件名 import java.io.File;import java.util.ArrayList;public class FileTest { private static ArrayList<String> filelist = new ArrayList<String>(); public static void main( String[] args ) throws Exception { String fileP...
java怎么读取某个文件夹下边的所有文件的名字?
public static void main(String[] args) throws Exception { String dirPath = "E:\/testFile";File dir = new File(dirPath);String[] subFileNames = dir.list();if(subFileNames != null && subFileNames.length > 0){ for(String subFileName : subFileNames){ System.out.println(...
java怎么循环读取目录下的文件内容
File[] files = dir.listFiles(); \/\/ 该文件目录下文件全部放入数组 if (files != null) { for (int i = 0; i < files.length; i++) { String fileName = files[i].getName();if (files[i].isDirectory()) { \/\/ 判断是文件还是文件夹 getFileList(files[i].getAbsolutePath())...
java如何遍历resources下某个文件夹当中的文件?求大神指导
在 Java 中遍历 resources 下的某个文件夹中的文件,可以采用两种方法。第一种方法是利用 ClassLoader 类的 getResource 或 getResources 方法获取资源路径,再结合 Files.walk 方法来遍历所有文件。具体步骤如下:1. 获取资源路径:URL url=getClass().getClassLoader().getResource("folderName");2....
java怎么获取resources下的文件路径
在Java中,可以通过`Class`类的`getResource`方法来获取resources目录下的文件路径。1. 使用Class类的getResource方法:在Java项目中,如果你想获取resources目录下的文件路径,可以使用`Class`类的`getResource`方法。这个方法能够返回一个`URL`对象,代表资源的路径。2. 相对路径和绝对路径:`getResource`...
java实现动态读取文件夹文件信息
import java.io.FileNotFoundException;import java.io.IOException;import java.io.File;public class ReadFile { public ReadFile() { } \/** * 动态读取某个文件夹下的所有文件信息 *\/ public static boolean readfile(String filepath) throws FileNotFoundException, IOException...
Java 读取配置文件
下面是相应的代码示例:使用java.lang.Class:获取xxx.class文件路径: xxx.class.getResource("").getPath 根据相对或绝对路径读取文件: xxx.class.getResource("fileName").getPath使用java.lang.ClassLoader:获取classes路径: xxx.class.getClassLoader().getResource("").getPath 获取classes目录下...