[Tex/LaTex] How to include Source Code by pointing to a File Path (recursively)

codejavalistingsmintedsourcecode

I'm looking for a way to include source code in my thesis' appendix.

Any chance to add source code by pointing to a directory and adding the java file recursively going through the packages?

I do and did already use minted and listings. Maybe I have missed a feature of these packages. But since the java source code might change, I would like to avoid copy&paste which increase the chance to miss something. Favourable it's done automatically.

Best Answer

To expand on my comment, you could always do something like this:

\documentclass{article}
\usepackage{pgffor}
\usepackage{listings}
\begin{document}

\foreach \java in  {hello, hello} {
   \begin{figure}[htpb]
        \lstinputlisting[language=java]{\java.java}
        \caption{Source code for \textsf{\java.java}}
     \label{fig:\java}
   \end{figure}
}

\end{document}

with output:

enter image description here

This does not recursively search for files but it will update when the source files change and it does minimize what you have to type by only requiring you to add the file names to the loop.

The MWE is more for proof of concept as you'd probably want to tweak the formatting and layout of the code. Personally, I'd never use figure, or floats in general, as I like text/environments to appear where I type them:). I just checked and, as I suspected, using figure causes problems when the source file is too long to fit on one page.

Related Question