Traversal means accessing each element once. For example, a binary tree. Traversing a binary tree means accessing each element in the binary tree once.
This example demonstrates the implementation of "specify the number of layers to traverse during file traversal".
1. Example code
package com.myjava.test;import java.io.File;import java.util.ArrayList;import java.util.List;public class JavaTest {/*** @param args*/public static void main(String[] args) {JavaTest jt = new JavaTest();String path = "E://filetest";File file = new File(path);try {jt.getFile(file, 0);}catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}int mDirLevel = 2;// Number of layers private void getFile(File file, int dirLevel) throws Exception {if (mDirLevel != -1 && dirLevel > mDirLevel) {dirLevel = 0;return;}if (file == null) {return;}if (file.exists()) {if (file.isFile()) {//do what?System.out.println("file:" + file.getAbsolutePath());} else {// Get all subfiles and subfolders in the current folder File files[] = file.listFiles();// Loop to process each object if (files == null) {return;}for (int i = 0; i < files.length; i++) {// Recursively call to process each file object getFile(files[i], dirLevel +1);}}}}}}} 2. Test results:
file:E:/filetest/f.txt
file:E:/filetest/f1/New text document - copy.txt
file:E:/filetest/f1/New text document.txt
file:E:/filetest/f1 - Copy/New text document.txt
Summarize
The above is the full content of this article about the detailed layer code for the specified traversal of Java programming file traversal. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!