DEV Community

Query Filter
Query Filter

Posted on

bridge100

private void writeToFile(String content) {
        try {
            // 1. Dynamically find the project root (climbing up from current dir)
            File projectRoot = findProjectRoot();

            // 2. Ensure we are targeting the /build folder at the root
            File buildDir = new File(projectRoot, "build");
            if (!buildDir.exists()) {
                buildDir.mkdirs();
            }

            File file = new File(buildDir, "spring-beans.dot");

            try (FileWriter writer = new FileWriter(file)) {
                writer.write(content);
            }

            // 3. Generate a proper URI for a clickable console link
            // In IntelliJ's terminal, this becomes a blue underline link.
            String fileUrl = file.toURI().toString();

            System.out.println("\n" + "=".repeat(60));
            System.out.println("GRAPH GENERATION SUCCESSFUL");
            System.out.println("Root Detected: " + projectRoot.getAbsolutePath());
            System.out.println("Click to open file: " + fileUrl);
            System.out.println("=".repeat(60) + "\n");

        } catch (IOException e) {
            System.err.println("CRITICAL: Failed to write DOT file: " + e.getMessage());
        }
    }

    /**
     * Climbs the directory tree to find the Gradle/Project root.
     */
    private File findProjectRoot() {
        String userDir = System.getProperty("user.dir");
        File current = new File(userDir);

        while (current != null) {
            // Look for Gradle markers to identify the project root
            if (new File(current, "build.gradle").exists() || 
                new File(current, "settings.gradle").exists() ||
                new File(current, "build.gradle.kts").exists()) {
                return current;
            }
            current = current.getParentFile();
        }

        // Fallback to current working directory if no root marker is found
        return new File(userDir);
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)