⑴ java怎麼遍歷一個盤下的所有文件
用遞歸演算法,遞歸可以理解成自己調用自己,但要有終止條件
首先是判斷這個是文件還是文件夾。文件的話就處理文件;文件夾的話,列出裡面的文件,再對每一個文件做同樣的判斷處理
下面是刪除一個文件夾(改成列出所有文件的話,你把刪除操作改成放入集合操作),所有刪除都是只能刪除一個文件或者是空文件夾,所以遇到文件夾就得把裡面的文件全部刪除
privatestaticvoiddeleteFile(Filefile){
if(!file.exists())
return;
System.out.print("刪除===");
if(file.isFile()){
System.out.println("文件:"+file);
file.delete();
}else{
System.out.println("文件夾:"+file);
for(Filef:file.listFiles()){
deleteFile(f);
}
file.delete();
}
}
同理(Node是自己定義的類,主要包含了name(String),children (List<Node>)這兩個屬性來表達層級):
遍歷了這個文件夾之後返回這個文件夾的Node作為上一個文件加的children之一,這就把文件夾的層級結構列出來了,當然你也可以用Map來存儲這些數據
/**
*列出文件目錄結構
*
*@paramfolder
*@paramfnf
*@return
*/
privatestaticNodelsFiles(Filefolder){
Noden=newNode();
n.setName(folder.getName());
n.setPath(folder.getAbsolutePath());
if(folder.isFile()){
n.setLeaf(true);
n.setSize(folder.length());
}else{
n.setLeaf(false);
File[]folders=folder.listFiles();//列出文件夾底下的文件
for(Filefile:folders){//遍歷每個文件做相同操作
Nodecn=lsFiles(file);
n.getChildren().add(cn);
n.setSize(n.getSize()+cn.getSize());
}
}
returnn;
}
下面是不分層次結構來列出所有文件(純手寫,可能有語法錯誤)
/**
*列出文件路徑
*
*@paramfolder
*@paramfnf
*@return
*/
privatestaticList<String>lsFiles(Filefolder){
List<String>l=newArrayList<String>();
l.add(folder.getAbsolutePath());
if(folder.isFile()){
//處理file
}else{
File[]folders=folder.listFiles();
for(Filefile:folders){
l.addAll(lsFiles(file));
}
}
returnl;
}
效果
⑵ 使用java遞歸方法遍歷指定目錄下所有子目錄和子文件
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* 讀取目錄及子目錄下指定文件名的路徑 並放到一個數組裡面返回遍歷
* @author zdz8207
*
*/
public class FileViewer {
public static void main(String[] args) {
//List arrayList = FileViewer.getListFiles("d:/com","html",true);
//讀取d:/com下的以java 結尾的文件 如有子目錄,包含之(後綴名為null則為所有文件)
//List arrayList = FileViewer.getListFiles("d:/com","java",true);
//經試驗,後綴不能不填寫,否則編譯不通過,提示「FileViewer.java:17: 非法的表達式開始」。
//另外後綴為""時的情況需要 增加到IF 里去,否則 後綴為""時,不會顯示所有文件
List arrayList = FileViewer.getListFiles("d:/com","",true);
if(arrayList.isEmpty())
{
System.out.println("沒有符號要求的文件");
}
else
{
String message = "";
message += "符號要求的文件數:" + arrayList.size() + "\r\n";
System.out.println(message);
for (Iterator i = arrayList.iterator(); i.hasNext();)
{
String temp = (String) i.next();
System.out.println(temp);
message += temp + "\r\n";
}
//將顯示的文件路徑寫到指定的文件里,若文件不存在,則提示IO異常
//java.io.FileNotFoundException: d:\ajax\menu.txt (系統找不到指定的路徑。)
//如果 加個文件是否存在的判斷,如不存在就在當前目錄新建一個,則更好。
appendMethod("d:/menu.txt",message);
}
}
public static List<String> fileList = new ArrayList<String>();
/**
*
* @param path 文件路徑
* @param suffix 後綴名
* @param isdepth 是否遍歷子目錄
* @return
*/
public static List getListFiles(String path, String suffix, boolean isdepth)
{
File file = new File(path);
return FileViewer.listFile(file ,suffix, isdepth);
}
public static List listFile(File f, String suffix, boolean isdepth)
{
//是目錄,同時需要遍歷子目錄
if (f.isDirectory() && isdepth == true)
{
File[] t = f.listFiles();
for (int i = 0; i < t.length; i++)
{
listFile(t[i], suffix, isdepth);
}
}
else
{
String filePath = f.getAbsolutePath();
System.out.println("suffix = "+suffix);
if(suffix =="" || suffix == null)
{
//後綴名為null則為所有文件
System.out.println("----------------");
fileList.add(filePath);
}
else
{
int begIndex = filePath.lastIndexOf(".");//最後一個.(即後綴名前面的.)的索引
String tempsuffix = "";
if(begIndex != -1)//防止是文件但卻沒有後綴名結束的文件
{
tempsuffix = filePath.substring(begIndex + 1, filePath.length());
}
if(tempsuffix.equals(suffix))
{
fileList.add(filePath);
}
System.out.println("|||||||||||||||||||");
}
}
return fileList;
}
/**
* 方法追加文件:使用FileWriter
* @param fileName
* @param content
*/
public static void appendMethod(String fileName, String content)
{
try
{
//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
FileWriter writer = new FileWriter(fileName, true);
writer.write(content + "\r\n");
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
⑶ java 最短路徑演算法 如何實現有向 任意兩點的最短路徑
Dijkstra(迪傑斯特拉)演算法是典型的最短路徑路由演算法,用於計算一個節點到其他所有節點的最短路徑。主要特點是以起始點為中心向外層層擴展,直到擴展到終點為止。
Dijkstra一般的表述通常有兩種方式,一種用永久和臨時標號方式,一種是用OPEN, CLOSE表方式
用OPEN,CLOSE表的方式,其採用的是貪心法的演算法策略,大概過程如下:
1.聲明兩個集合,open和close,open用於存儲未遍歷的節點,close用來存儲已遍歷的節點
2.初始階段,將初始節點放入close,其他所有節點放入open
3.以初始節點為中心向外一層層遍歷,獲取離指定節點最近的子節點放入close並從新計算路徑,直至close包含所有子節點
代碼實例如下:
Node對象用於封裝節點信息,包括名字和子節點
[java] view plain
public class Node {
private String name;
private Map<Node,Integer> child=new HashMap<Node,Integer>();
public Node(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<Node, Integer> getChild() {
return child;
}
public void setChild(Map<Node, Integer> child) {
this.child = child;
}
}
MapBuilder用於初始化數據源,返回圖的起始節點
[java] view plain
public class MapBuilder {
public Node build(Set<Node> open, Set<Node> close){
Node nodeA=new Node("A");
Node nodeB=new Node("B");
Node nodeC=new Node("C");
Node nodeD=new Node("D");
Node nodeE=new Node("E");
Node nodeF=new Node("F");
Node nodeG=new Node("G");
Node nodeH=new Node("H");
nodeA.getChild().put(nodeB, 1);
nodeA.getChild().put(nodeC, 1);
nodeA.getChild().put(nodeD, 4);
nodeA.getChild().put(nodeG, 5);
nodeA.getChild().put(nodeF, 2);
nodeB.getChild().put(nodeA, 1);
nodeB.getChild().put(nodeF, 2);
nodeB.getChild().put(nodeH, 4);
nodeC.getChild().put(nodeA, 1);
nodeC.getChild().put(nodeG, 3);
nodeD.getChild().put(nodeA, 4);
nodeD.getChild().put(nodeE, 1);
nodeE.getChild().put(nodeD, 1);
nodeE.getChild().put(nodeF, 1);
nodeF.getChild().put(nodeE, 1);
nodeF.getChild().put(nodeB, 2);
nodeF.getChild().put(nodeA, 2);
nodeG.getChild().put(nodeC, 3);
nodeG.getChild().put(nodeA, 5);
nodeG.getChild().put(nodeH, 1);
nodeH.getChild().put(nodeB, 4);
nodeH.getChild().put(nodeG, 1);
open.add(nodeB);
open.add(nodeC);
open.add(nodeD);
open.add(nodeE);
open.add(nodeF);
open.add(nodeG);
open.add(nodeH);
close.add(nodeA);
return nodeA;
}
}
圖的結構如下圖所示:
Dijkstra對象用於計算起始節點到所有其他節點的最短路徑
[java] view plain
public class Dijkstra {
Set<Node> open=new HashSet<Node>();
Set<Node> close=new HashSet<Node>();
Map<String,Integer> path=new HashMap<String,Integer>();//封裝路徑距離
Map<String,String> pathInfo=new HashMap<String,String>();//封裝路徑信息
public Node init(){
//初始路徑,因沒有A->E這條路徑,所以path(E)設置為Integer.MAX_VALUE
path.put("B", 1);
pathInfo.put("B", "A->B");
path.put("C", 1);
pathInfo.put("C", "A->C");
path.put("D", 4);
pathInfo.put("D", "A->D");
path.put("E", Integer.MAX_VALUE);
pathInfo.put("E", "A");
path.put("F", 2);
pathInfo.put("F", "A->F");
path.put("G", 5);
pathInfo.put("G", "A->G");
path.put("H", Integer.MAX_VALUE);
pathInfo.put("H", "A");
//將初始節點放入close,其他節點放入open
Node start=new MapBuilder().build(open,close);
return start;
}
public void computePath(Node start){
Node nearest=getShortestPath(start);//取距離start節點最近的子節點,放入close
if(nearest==null){
return;
}
close.add(nearest);
open.remove(nearest);
Map<Node,Integer> childs=nearest.getChild();
for(Node child:childs.keySet()){
if(open.contains(child)){//如果子節點在open中
Integer newCompute=path.get(nearest.getName())+childs.get(child);
if(path.get(child.getName())>newCompute){//之前設置的距離大於新計算出來的距離
path.put(child.getName(), newCompute);
pathInfo.put(child.getName(), pathInfo.get(nearest.getName())+"->"+child.getName());
}
}
}
computePath(start);//重復執行自己,確保所有子節點被遍歷
computePath(nearest);//向外一層層遞歸,直至所有頂點被遍歷
}
public void printPathInfo(){
Set<Map.Entry<String, String>> pathInfos=pathInfo.entrySet();
for(Map.Entry<String, String> pathInfo:pathInfos){
System.out.println(pathInfo.getKey()+":"+pathInfo.getValue());
}
}
/**
* 獲取與node最近的子節點
*/
private Node getShortestPath(Node node){
Node res=null;
int minDis=Integer.MAX_VALUE;
Map<Node,Integer> childs=node.getChild();
for(Node child:childs.keySet()){
if(open.contains(child)){
int distance=childs.get(child);
if(distance<minDis){
minDis=distance;
res=child;
}
}
}
return res;
}
}
Main用於測試Dijkstra對象
[java] view plain
public class Main {
public static void main(String[] args) {
Dijkstra test=new Dijkstra();
Node start=test.init();
test.computePath(start);
test.printPathInfo();
}
}
⑷ JAVA文件目錄遍歷縮進演算法
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileFilter;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.*;
import javax.swing.tree.*;
public class MainFrame extends JFrame {
private JScrollPane imagesp = new JScrollPane();
private JTree tree = new JTree(FileTreeNode.ROOT);
private TreePath lastFilePath;
private JButton scaleB = new JButton("放大");
private JButton scaleS = new JButton("縮小");
private Image img;
private float beishu = 1;
public static void main(String[] args) {
new MainFrame();
}
public MainFrame () {
scaleB.setEnabled(false);
scaleS.setEnabled(false);
this.setSize(400,400);
this.setLayout(new BorderLayout());
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(1,2));
JScrollPane treesp = new JScrollPane();
treesp.setViewportView(tree);
centerPanel.add(treesp);
tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent event) {
TreePath treePath = tree.getSelectionPath();
if(treePath!=lastFilePath) {
FileTreeNode node = (FileTreeNode)treePath.getLastPathComponent();
if(node.isFile()) {
String fpath = node.getPath();
lastFilePath = treePath;
img = Toolkit.getDefaultToolkit().createImage(fpath);
imagesp.setViewportView(new JLabel(new ImageIcon(img)));
beishu = 1;
imagesp.repaint();
scaleB.setEnabled(true);
scaleS.setEnabled(true);
}
}
}
});
centerPanel.add(imagesp);
this.add(centerPanel,BorderLayout.CENTER);
JPanel btnPanel = new JPanel();
btnPanel.add(scaleB);
btnPanel.add(scaleS);
scaleB.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
beishu*=2;
Image scaleIMG = img.getScaledInstance((int)(img.getWidth(imagesp)*beishu), (int)(img.getHeight(imagesp)*beishu), Image.SCALE_DEFAULT);
imagesp.setViewportView(new JLabel(new ImageIcon(scaleIMG)));
imagesp.repaint();
}
});
scaleS.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
beishu/=2;
Image scaleIMG = img.getScaledInstance((int)(img.getWidth(imagesp)*beishu), (int)(img.getHeight(imagesp)*beishu), Image.SCALE_DEFAULT);
imagesp.setViewportView(new JLabel(new ImageIcon(scaleIMG)));
imagesp.repaint();
}
});
this.add(btnPanel,BorderLayout.SOUTH);
this.setVisible(true);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
class FileTreeNode implements TreeNode {
private String name;
private String path;
private boolean isFile;
private Vector<FileTreeNode> children;
private FileTreeNode parent;
private final static ImageFileFilter filter = new ImageFileFilter();
public final static FileTreeNode ROOT = new FileTreeNode("我的電腦","",null);
private FileTreeNode(String name, String path, FileTreeNode parent) {
this.name = name;
this.path = path;
this.parent = parent;
File f = new File(path);
if(f.isFile())isFile = true;
else isFile = false;
}
public Enumeration<FileTreeNode> children() {
if(children==null)initChild();
return children.elements();
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public boolean isFile() {
return isFile;
}
public boolean getAllowsChildren() {
return !isFile;
}
public TreeNode getChildAt(int childIndex) {
if(children==null)initChild();
return children.elementAt(childIndex);
}
public int getChildCount() {
if(children==null)initChild();
return children.size();
}
public int getIndex(TreeNode node) {
return children.indexOf(node);
}
public TreeNode getParent() {
return parent;
}
public boolean isLeaf() {
return isFile;
}
public String toString() {
return name;
}
private void initChild() {
if(this==ROOT) {
children = new Vector<FileTreeNode>();
File[] files = File.listRoots();
for(int i=0;i<files.length;i++) {
FileTreeNode child = new FileTreeNode(files[i].getPath(),files[i].getPath(),this);
children.add(child);
}
}else {
children = new Vector<FileTreeNode>();
File current = new File(path);
if(current.isDirectory()) {
File[] files = current.listFiles(filter);//filefilter to add
for(int i=0;i<files.length;i++) {
FileTreeNode child = new FileTreeNode(files[i].getName(),files[i].getPath(),this);
children.add(child);
}
}
}
}
}
class ImageFileFilter implements FileFilter {
public boolean accept(File pathname) {
if(pathname.isDirectory())return true;
else {
String name = pathname.getName();
return match(name);
}
}
private boolean match(String name) {
if(name.endsWith("jpg"))return true;
else if(name.endsWith("gif"))return true;
else if(name.endsWith("bmp"))return true;
return false;
}
}
其實是給另一個問題寫的,不過別個已經結了。損失好多分呀。
現在只顯示3種文件類型,把FileFilter去掉就行了。
⑸ java遍歷一個目錄,輸出這個那些最少一個文件的那些目錄的絕對路徑,這道題如何用java代碼解決
我就不多說了,直接上代碼吧:
/**
*java遍歷一個目錄,輸出這個那些最少一個文件的那些目錄的絕對路徑,這道題如何用java代碼解決?
*
*@paramargs
*/
publicstaticvoidmain(String[]args){
//設置文件目錄,設置為user.dir目錄,便於測試
Filefolder=newFile(System.getProperty("user.dir"));
System.out.println("根目錄:"+folder.getAbsolutePath());
System.out.println("---------------------------------------------------------------------------");
(folder);
System.out.println("---------------------------------------------------------------------------");
}
/**
*顯示有一個文件以上的文件目錄
*@paramfile文件或目錄
*/
privatestaticvoid(Filefile){
if(file!=null){
if(file.isDirectory()){//只有目錄才處理
File[]files=file.listFiles();
intfileCount=0;//文件數量,即不是文件夾的數量
if(null!=files&&files.length>0){
for(FilesubFile:files){
if(subFile.isFile()){
fileCount++;//文件數目加一
}else{
//繼續檢查下面的文件夾
(subFile);
}
}
}
if(fileCount>0){//說明有文件,需要顯示文件夾的全路徑
System.out.println(file.getAbsolutePath()+":共有文件"+fileCount+"個!");
}
}
}
}
在我機器上的運行結果為:
⑹ JAVA7如何遍歷一個目錄下的所有文件,如何知
1.遍歷本目錄下所有的文件(不包括目錄的目錄里的文件)
import java.io.File;public class main { public static void main(String[] args) { String path = "D:\\JAVA"; //要遍歷的路徑 File file = new File(path); //獲取其file對象 File[] fs = file.listFiles(); //遍歷path下的文件和目錄,放在File數組中 for(File f:fs){ //遍歷File[]數組 if(!f.isDirectory()) //若非目錄(即文件),則列印 System.out.println(f); } }}
運行結果:
列印出 D:/JAVA下的全部文件(包括D:/JAVA下的目錄下的文件)
1.遍歷本目錄下所有的文件(包括目錄的目錄里的文件)
import java.io.File;import java.io.FileFilter;public class FileText { public static void main(String[] args) { String path = "D:\\JAVA"; //要遍歷的路徑 File file = new File(path); //獲取其file對象 func(file); } private static void func(File file){ File[] fs = file.listFiles(); for(File f:fs){ if(f.isDirectory()) //若是目錄,則遞歸列印該目錄下的文件 func(f); if(f.isFile()) //若是文件,直接列印 System.out.println(f); } }}
列印結果:
列印所有文件
⑺ 在java中如何遍歷某個路徑下的所有文件夾和文件
首先,我們先來遍歷一下D盤根目錄下所有的子文件:public
static
void
fileList()
{
File
file=new
File("d:/");
File[]
files
=
file.listFiles();
if
(files
!=
null)
{
for
(File
f
:
files)
{
System.out.println(f.getPath());
}
}
}對此,我們肯定不滿足,我們需要遍歷D盤下所有的文件和文件夾,而不是根目錄下的文件夾,這個時候我們需要使用到遞歸:public
static
void
fileList(File
file)
{
File[]
files
=
file.listFiles();
if
(files
!=
null)
{
for
(File
f
:
files)
{
System.out.println(f.getPath());
fileList(f);
}
}
}然後在主函數中調用:public
static
void
main(String[]
args)
{
File
file=new
File("d:/");
fileList(file);
}結果是不是能令你滿意呢?顯然,輸出的都是全路徑,我們可以對我們的遞歸函數做如下改進:
public
static
void
fileList(File
file,int
node)
{
node++;
File[]
files
=
file.listFiles();
if
(files
!=
null)
{
for
(File
f
:
files)
{
for(int
i=0;i<node;i++){
if(i==node-1){
System.out.print("├");
}
else{
System.out.print("
");
}
}
System.out.println(f.getName());
fileList(f,node);
}
}
}然後再次在主函數中調用:public
static
void
main(String[]
args)
{
File
file=new
File("d:/");
fileList(file,0);
}得到的結果是一個類似樹狀的結構,如果你對此還不滿意,可以嘗試給JTree上添加節點,可以做到和資源管理器中一樣的結構。
⑻ 用java怎麼遍歷磁碟上的所有文件
首先,我們需要獲取磁碟中所有的盤符路徑:jdk6中一個方法搞定:
File[]roots=File.listRoots();
然後,通過每個路徑來進行向下遍歷,上代碼(手敲,各種小錯誤別怪我,看思路就好):
importjava.io.File;
/**
由於本人使用了junit,請自行添加main方法測試
*/
publicclassTest{
@org.junit.Test
publicvoidtestfiles(){
File[]roots=File.listRoots();
for(Filef:roots){
System.out.println(f.getAbsolutePath());
}
listFiles(roots);
}
publicvoidlistFiles(File[]files){
if(files==null||files.length==0)return;
for(Filef:files){
if(f.isDirectory()){
System.out.println(f.getAbsolutePath());
listFiles(f.listFiles());
}else{
System.out.println(" |"+f.getName());
}
}
}
}
⑼ java中如何遍歷最短路徑長度鄰接矩陣
packagetest;
importjava.util.ArrayList;
importjava.util.List;
/**
*java-用鄰接矩陣求圖的最短路徑、最長途徑。弗洛伊德演算法
*/
publicclassFloydInGraph{
privatestaticintINF=Integer.MAX_VALUE;
privateint[][]dist;
privateint[][]path;
privateList<Integer>result=newArrayList<Integer>();
publicFloydInGraph(intsize){
this.path=newint[size][size];
this.dist=newint[size][size];
}
publicvoidfindPath(inti,intj){
intk=path[i][j];
if(k==-1)return;
findPath(i,k);
result.add(k);
findPath(k,j);
}
publicvoidfindCheapestPath(intbegin,intend,int[][]matrix){
floyd(matrix);
result.add(begin);
findPath(begin,end);
result.add(end);
}
publicvoidfloyd(int[][]matrix){
intsize=matrix.length;
for(inti=0;i<size;i++){
for(intj=0;j<size;j++){
path[i][j]=-1;
dist[i][j]=matrix[i][j];
}
}
for(intk=0;k<size;k++){
for(inti=0;i<size;i++){
for(intj=0;j<size;j++){
if(dist[i][k]!=INF&&
dist[k][j]!=INF&&
dist[i][k]+dist[k][j]<dist[i][j]){//dist[i][k]+dist[k][j]>dist[i][j]-->longestPath
dist[i][j]=dist[i][k]+dist[k][j];
path[i][j]=k;
}
}
}
}
}
publicstaticvoidmain(String[]args){
FloydInGraphgraph=newFloydInGraph(5);
int[][]matrix={
{INF,30,INF,10,50},
{INF,INF,60,INF,INF},
{INF,INF,INF,INF,INF},
{INF,INF,INF,INF,30},
{50,INF,40,INF,INF},
};
intbegin=0;
intend=4;
graph.findCheapestPath(begin,end,matrix);
List<Integer>list=graph.result;
System.out.println(begin+"to"+end+",thecheapestpathis:");
System.out.println(list.toString());
System.out.println(graph.dist[begin][end]);
}
}
為了避免目錄列舉消耗時間過長,請指定一個目錄來模擬,命令行參數:代表路徑的字元串.
如果認可代碼,請加分50,謝謝
----
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.io.*;
final public class FileTree extends JFrame {
public FileTree(File dir) throws HeadlessException {
super("File Tree");
JTree tree;
add(new JScrollPane(tree =new JTree(buildTreeModel(dir))));
tree.setCellRenderer(new FileTreeRenderer());
setSize(400,600);
setVisible(true);
}
private TreeModel buildTreeModel(File dir){
DefaultMutableTreeNode root = new DefaultMutableTreeNode(dir);
walkthrough(dir,root);
return new DefaultTreeModel(root);
}
private static void walkthrough(File f,DefaultMutableTreeNode node){
for (File fle : f.listFiles()) {
DefaultMutableTreeNode n = new DefaultMutableTreeNode(fle);
node.add(n);
if (fle.isDirectory()){
walkthrough(fle, n);
}
}
}
private class FileTreeRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
JLabel cmp = (JLabel)super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode n = (DefaultMutableTreeNode)value;
Object obj = n.getUserObject();
if (obj instanceof File) {
File f = (File)obj;
cmp.setText(f.getName());
cmp.setForeground(f.isDirectory()?Color.BLUE:Color.BLACK);
}
}
return cmp;
}
}
public static void main(String[] args) {
new FileTree(new File(args[0]));
}
}