使用java递归方法遍历指定目录下所有子目录和子文件

使用java递归方法遍历指定目录下所有子目录和子文件,第1张

import javaio;

import javautilArrayList;

import javautilIterator;

import javautilList;

/

读取目录及子目录下指定文件名的路径 并放到一个数组里面返回遍历

@author zdz8207

/

public class FileViewer {

public static void main(String[] args) {

//List arrayList = FileViewergetListFiles("d:/com","html",true);

//读取d:/com下的以java 结尾的文件 如有子目录,包含之(后缀名为null则为所有文件)

//List arrayList = FileViewergetListFiles("d:/com","java",true);

//经试验,后缀不能不填写,否则编译不通过,提示“FileViewerjava:17: 非法的表达式开始”。

//另外后缀为""时的情况需要 增加到IF 里去,否则 后缀为""时,不会显示所有文件

List arrayList = FileViewergetListFiles("d:/com","",true);

if(arrayListisEmpty())

{

Systemoutprintln("没有符号要求的文件");

}

else

{

String message = "";

message += "符号要求的文件数:" + arrayListsize() + "\r\n";

Systemoutprintln(message);

for (Iterator i = arrayListiterator(); ihasNext();)

{

String temp = (String) inext();

Systemoutprintln(temp);

message += temp + "\r\n";

}

//将显示的文件路径写到指定的文件里,若文件不存在,则提示IO异常

//javaioFileNotFoundException: d:\ajax\menutxt (系统找不到指定的路径。)

//如果 加个文件是否存在的判断,如不存在就在当前目录新建一个,则更好。

appendMethod("d:/menutxt",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 FileViewerlistFile(file ,suffix, isdepth);

}

public static List listFile(File f, String suffix, boolean isdepth)

{

//是目录,同时需要遍历子目录

if (fisDirectory() && isdepth == true)

{

File[] t = flistFiles();

for (int i = 0; i < tlength; i++)

{

listFile(t[i], suffix, isdepth);

}

}

else

{

String filePath = fgetAbsolutePath();

Systemoutprintln("suffix = "+suffix);

if(suffix =="" || suffix == null)

{

//后缀名为null则为所有文件

Systemoutprintln("----------------");

fileListadd(filePath);

}

else

{

int begIndex = filePathlastIndexOf("");//最后一个(即后缀名前面的)的索引

String tempsuffix = "";

if(begIndex != -1)//防止是文件但却没有后缀名结束的文件

{

tempsuffix = filePathsubstring(begIndex + 1, filePathlength());

}

if(tempsuffixequals(suffix))

{

fileListadd(filePath);

}

Systemoutprintln("|||||||||||||||||||");

}

}

return fileList;

}

/

方法追加文件:使用FileWriter

@param fileName

@param content

/

public static void appendMethod(String fileName, String content)

{

try

{

//打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件

FileWriter writer = new FileWriter(fileName, true);

writerwrite(content + "\r\n");

writerclose();

}

catch (IOException e)

{

eprintStackTrace();

}

}

}

java获取根路径有两种方式:

1)在servlet可以用一下方法取得:

requestgetRealPath(“/”)

例如:filepach = requestgetRealPath(“/”)+”//upload//”;

2)不从jsp,或servlet中获取,只从普通java类中获取:

String path = getClass()getProtectionDomain()getCodeSource()getLocation()getPath();

SAXReader() saxReader = new SAXReader();

if(pathindexOf(“WEB-INF”)>0){

path = pathsubstring(0,pathindexOf(“/WEB-INF/classes”)+16);

// ‘/WEB-INF/classes’为16位

document = saxReaderread(path+filename);

}else{

document = saxReaderread(getClass()getResourceAsStream(filename));

}

package tree;

import javautilLinkedList;

import javautilList;

/

功能:把一个数组的值存入二叉树中,然后进行3种方式的遍历

参考资料0:数据结构(C语言版)严蔚敏

参考资料1:>

TreeItem parentItem=itemgetParentItem();得到父节点

Tree tree= itemgetParent();得到树

parentItemgetText();节点显示的值

parentItemgetData();item上保存的数据

packaged;

importjavaio;

importjavautil;

publicclassTreemap{

staticTreeMaptm=newTreeMap();//实例化一个树对象

staticStudents;//声明一个静态变量S

publicstaticvoidmain(Stringargs[]){

try{

fis=new("studentstxt");//实例化一个对象并且读取studentstxt文件

ois=new(fis);

while((s=(Student)(oisreadObject()))!=null)

{

tmput(sstunum,s);

}

oisclose();

}catch(IOExceptionioe){

}catch(c){

}

try{

while(true){

Systemoutprintln("[0]主菜单[1]查找[2]输入[3]删除[4]全部列出[5]退出");//显示菜单

Systemoutprint("请选择 *** 作:");

is=new(Systemin);

br=new(is);

Stringch=brreadLine();

intc=IntegerparseInt(ch);

switch(c){

case0:

break;

case1:

search();

break;

case2:

input();

break;

case3:

delete();

break;

case4:

listAll();

break;

case5:

tmclear();

Systemexit(0);

break;

default:

Systemoutprintln("输入有误!");

}

}

}catch(IOExceptione){

}catch(e){

Systemoutprintln("输入有误!");

}

}

staticvoidlistAll()

{

tmclear();

try{

fis=new("studentsdat");

ois=new(fis);

while((s=(Student)(oisreadObject()))!=null)

{

tmput(sstunum,s);

Systemoutprintln(sstunum""sstuname);

}

oisclose();

}catch(IOExceptionioe){

}catch(c){

}

}

staticvoidinput(){

Stringstr1=null,str2=null;

try{

InputStreamReaderis=newInputStreamReader(Systemin);

BufferedReaderbr=newBufferedReader(is);

Systemoutprint("请输入学号:");

str1=brreadLine();

Systemoutprint("请输入姓名:");

str2=brreadLine();

}catch(IOExceptione){

Systemoutprintln(e);

}

s=newStudent(str1,str2);

tmput(sstunum,s);

//写文件

intn=1;

try{

FileOutputStreamfos=newFileOutputStream("studentsdat");

ObjectOutputStreamoos=newObjectOutputStream(fos);

for(Iteratorit=tmvalues()iterator();ithasNext();)

{

s=(Student)itnext();

ooswriteObject(s);

}

oosclose();

}catch(IOExceptione){

Systemoutprintln(e);

}

}

staticvoidsearch()

{

Stringkey=null;

try{

InputStreamReaderis=newInputStreamReader(Systemin);

BufferedReaderbr=newBufferedReader(is);

Systemoutprint("请输入一个学号:");

key=brreadLine();

}catch(IOExceptione){

Systemoutprintln(e);

}

if(tmcontainsKey(key))

{

s=(Student)tmget(key);

Systemoutprintln(sstunum""sstuname);

}

else

Systemoutprintln("没有");

}

staticvoiddelete()

{

Stringkey=null;

try{

InputStreamReaderis=newInputStreamReader(Systemin);

BufferedReaderbr=newBufferedReader(is);

Systemoutprint("请输入学号:");

key=brreadLine();

}catch(IOExceptione){

}

if(tmremove(key)equals(null))

{

Systemoutprintln("没有");

}

try{

FileOutputStreamfos=newFileOutputStream("studentsdat");

ObjectOutputStreamoos=newObjectOutputStream(fos);

for(Iteratorit=tmvalues()iterator();ithasNext();)

{

s=(Student)itnext();

ooswriteObject(s);

}

oosclose();

}catch(IOExceptione){

Systemoutprintln(e);

}

}

}

classStudentimplementsSerializable{

Stringstunum;

Stringstuname;

publicStudent(Stringstunum,Stringstuname){

thisstunum=stunum;

thisstuname=stuname;

}

}

1、面向对象思想的继承是子类继承父类,父类被其它子类继承在JAVA虚拟机的容器中并没有直接接口获取;

2、如果是在一个项目内获取父类的子类继承情况,参考这个代码:

package find;

import javaioFile;

import javaioIOException;

import javanetURL;

import javautilArrayList;

import javautilList;

import findtestIntf;

import findtestMan;

public class ClassUtil {

public static void main(String[] args) {

try {

Systemoutprintln("接口实现类:");

for (Class<> c : getAllAssignedClass(Intfclass)) {

Systemoutprintln(cgetName());

}

Systemoutprintln("子类:");

for (Class<> c : getAllAssignedClass(Manclass)) {

Systemoutprintln(cgetName());

}

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

/

 获取同一路径下所有子类或接口实现类

 

 @param intf

 @return

 @throws IOException

 @throws ClassNotFoundException

/

public static List<Class<>> getAllAssignedClass(Class<> cls) throws IOException,

ClassNotFoundException {

List<Class<>> classes = new ArrayList<Class<>>();

for (Class<> c : getClasses(cls)) {

if (clsisAssignableFrom(c) && !clsequals(c)) {

classesadd(c);

}

}

return classes;

}

/

 取得当前类路径下的所有类

 

 @param cls

 @return

 @throws IOException

 @throws ClassNotFoundException

/

public static List<Class<>> getClasses(Class<> cls) throws IOException,

ClassNotFoundException {

String pk = clsgetPackage()getName();

String path = pkreplace('', '/');

ClassLoader classloader = ThreadcurrentThread()getContextClassLoader();

URL url = classloadergetResource(path);

return getClasses(new File(urlgetFile()), pk);

}

/

 迭代查找类

 

 @param dir

 @param pk

 @return

 @throws ClassNotFoundException

/

private static List<Class<>> getClasses(File dir, String pk) throws ClassNotFoundException {

List<Class<>> classes = new ArrayList<Class<>>();

if (!direxists()) {

return classes;

}

for (File f : dirlistFiles()) {

if (fisDirectory()) {

classesaddAll(getClasses(f, pk + "" + fgetName()));

}

String name = fgetName();

if (nameendsWith("class")) {

classesadd(ClassforName(pk + "" + namesubstring(0, namelength() - 6)));

}

}

return classes;

}

}

我给你写了一个例子 你看看吧 你看了就明白了

package tree;

import javaawtComponent;

import javaawtDimension;

import javaawtEvent;

import javaawtToolkit;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaawteventMouseAdapter;

import javaawteventMouseEvent;

import javabeansbeancontextBeanContext;

import javaxswingJFrame;

import javaxswingJLabel;

import javaxswingJMenuItem;

import javaxswingJPopupMenu;

import javaxswingJScrollPane;

import javaxswingJTextField;

import javaxswingJTree;

import javaxswingeventTreeSelectionEvent;

import javaxswingeventTreeSelectionListener;

import javaxswingtableDefaultTableModel;

import javaxswingtreeDefaultMutableTreeNode;

import javaxswingtreeDefaultTreeModel;

import comsunxmlinternalmessagingsaajpackagingmimeutilBEncoderStream;

public class MainFrame extends JFrame {

public static void main(String args[]) {

try {

MainFrame frame = new MainFrame();

Dimension frameSize = framegetSize();

Dimension screenSize = ToolkitgetDefaultToolkit()getScreenSize();

if(frameSizewidth>screenSizewidth){

frameSizewidth=screenSizewidth;

}

if(frameSizeheight>screenSizeheight){

frameSizeheight=screenSizeheight;

}

framesetLocation((screenSizewidth-frameSizewidth)/2, (screenSizeheight-frameSizeheight)/2);

framesetVisible(true);

} catch (Exception e) {

eprintStackTrace();

}

}

private JTree tree;

private DefaultMutableTreeNode root = new DefaultMutableTreeNode("语言");

private DefaultMutableTreeNode menu_accp = new DefaultMutableTreeNode("英语");

private DefaultMutableTreeNode menu_benet = new DefaultMutableTreeNode("法语");

private DefaultMutableTreeNode menu_accp_s1 = new DefaultMutableTreeNode("4级");

private DefaultMutableTreeNode menu_accp_s2 = new DefaultMutableTreeNode("6级");

private DefaultMutableTreeNode menu_accp_y2 = new DefaultMutableTreeNode("8级");

private JTextField txtParent;

private JTextField txtNode;

private JTextField txtType;

private JTextField txtChild;

private JPopupMenu popupMenu;

/

Create the frame

/

public MainFrame() {

super();

getContentPane()setLayout(null);

setBounds(100, 100, 535, 375);

setDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

final JScrollPane scrollPane = new JScrollPane();

scrollPanesetBounds(24, 10, 173, 317);

getContentPane()add(scrollPane);

tree = new JTree(root);

treeaddMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

if(egetModifiers()==EventMETA_MASK){

addPopup(getContentPane(), popupMenu);

popupMenushow(getContentPane(),egetX()+30,egetY()+40);

}

}

});

treeaddTreeSelectionListener(new TreeSelectionListener() {

public void valueChanged(TreeSelectionEvent e) {

DefaultMutableTreeNode node = (DefaultMutableTreeNode) treegetLastSelectedPathComponent();

Object nodeInfo = nodegetUserObject();

if(nodeisRoot()){

txtParentsetText("");

txtNodesetText(nodeInfotoString());

txtTypesetText("根节点");

txtChildsetText(nodegetChildCount() + "");

}else{

txtParentsetText(nodegetParent()toString());

txtNodesetText(nodeInfotoString());

if(nodeisLeaf()){

txtTypesetText("叶节点");

}else{

txtTypesetText("枝节点");

}

txtChildsetText(nodegetChildCount() + "");

}

}

});

scrollPanesetViewportView(tree);

txtParent = new JTextField();

txtParentsetBounds(339, 49, 90, 21);

getContentPane()add(txtParent);

txtNode = new JTextField();

txtNodesetBounds(339, 107, 90, 21);

getContentPane()add(txtNode);

txtType = new JTextField();

txtTypesetBounds(339, 167, 90, 21);

getContentPane()add(txtType);

txtChild = new JTextField();

txtChildsetBounds(339, 231, 90, 21);

getContentPane()add(txtChild);

final JLabel label = new JLabel();

labelsetText("父类型节点");

labelsetBounds(225, 49, 90, 15);

getContentPane()add(label);

final JLabel label_1 = new JLabel();

label_1setText("节点的名称");

label_1setBounds(225, 107, 90, 15);

getContentPane()add(label_1);

final JLabel label_2 = new JLabel();

label_2setText("节点的类型");

label_2setBounds(225, 167, 90, 15);

getContentPane()add(label_2);

final JLabel label_3 = new JLabel();

label_3setText("子节点的个数");

label_3setBounds(225, 231, 90, 15);

getContentPane()add(label_3);

popupMenu = new JPopupMenu();

final JMenuItem menuItem = new JMenuItem();

menuItemaddActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

DefaultMutableTreeNode node = (DefaultMutableTreeNode) treegetLastSelectedPathComponent();

DefaultTreeModel model = (DefaultTreeModel) treegetModel();

modelremoveNodeFromParent(node);

}

});

menuItemsetText("删除");

popupMenuadd(menuItem);

//

}

private static void addPopup(Component component, final JPopupMenu popup) {

componentaddMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

if (eisPopupTrigger())

showMenu(e);

}

public void mouseReleased(MouseEvent e) {

if (eisPopupTrigger())

showMenu(e);

}

private void showMenu(MouseEvent e) {

popupshow(egetComponent(), egetX(), egetY());

}

});

}

}

以上就是关于使用java递归方法遍历指定目录下所有子目录和子文件全部的内容,包括:使用java递归方法遍历指定目录下所有子目录和子文件、java怎么取到web服务的根路径、如何用Java实现树形结构啊等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/10076856.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-05
下一篇2023-05-05

发表评论

登录后才能评论

评论列表(0条)

    保存