I would like to explore several java files in the target directory and earn the defined class name.For example, if you have target_dir/Car.java Train.java, I would like to receive the class names Car and Train.Also, instead of simply returning the file name as a class name, I would like to take the form of searching the file one by one.I've created it, but I can only read one java file and I can't think of a solution.I would appreciate it if you could let me know if there are any corrections and better implementation methods.
importos
for root, dirs, files in os.walk(top='./target_dir'):
for file in files:
if not file.lower().endswith('.java')):
continue
filePath=os.path.join(root,file)
# read line by line
with open(filePath) asf:
lines=f.readlines()
# omit line breaks
lines = [ line.rstrip('\n') .split() for line in lines ]
print(lines)
# Display the code that follows the class description
for i in range (len(lines)) :
if "class" in lines [i]:
classline=lines[i]
print(classline)
print(classline [classline.index("class")+1])
This example shows how to enumerate class names using a regular expression.
sample code
import glob
import re
dir_path=r"./target_dir"
pattern=re.compile(r"\s?class\s+(\w+)")
for path in glob.glob(rf "{dir_path}/*.java"):
with open(path, "r", encoding="sjis") asf:
s=f.read()
for min re.finder (pattern, s):
class_name = m.group(1)
The print(f'{class_name} class was found in "{f.name}".')
© 2025 OneMinuteCode. All rights reserved.