English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Code of File Traversal at Specified Level in Java Programming

Traversal means visiting each element once. For example, in a binary tree, traversing the binary tree means visiting each element in the binary tree once.

This example demonstrates the implementation of "specifying the level of 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 block
			e.printStackTrace();
		}
	}
	int mDirLevel = 2;
	//Level
	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());
			}
				// Get all sub-files and sub-folders under the current folder
				File files[] = file.listFiles();
				// Loop through each object
				if (files == null) {
					return;
				}
				for (int i = 0; i < files.length; i++) {
					// Recursive call, 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

Summary

This is the complete detailed code of the specified level traversal of Java programming file traversal, I hope it will be helpful to everyone. Those who are interested can continue to read other related topics on this site, and welcome to leave messages to point out any deficiencies. Thank you for the support of friends to this site!

Statement: The content of this article is from the Internet, and the copyright is owned by the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to notice#w.3Please send an email to codebox.com (replace # with @ when sending email) to report violations, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.

You May Also Like