How can I move all java source files to their respective package directory?

Solution 1:

#Loop through the java files
for f in *.java; do

    # Get the package name (com.pkgX)
    package=$(grep -m 1 -Po "(?<=^package )[^; ]*" "$f")

    # Replace . with / and add src/ at the beginning
    target_folder="src/${package//./\/}"

    # Create the target folder
    mkdir -p "$target_folder"

    # move the file to the target folder
    mv "$f" "$target_folder"

done

Solution 2:

Here's a Python version:

#!/usr/bin/env python3
from pathlib import Path
from javalang.parse import parse  # $ pip install javalang

for java_src_path in Path().glob('*.java'):
    tree = parse(java_src_path.read_text())
    package_path = Path('src', *tree.package.name.split('.'))
    package_path.mkdir(parents=True, exist_ok=True)
    java_src_path.replace(package_path / java_src_path.name)

It uses javalang parser, to parse Java source code. I was just interested how it may look like. The regex-based bash version from @RoVo's answer should be fine.