I did write it to have a solution for my problem. But I don't know if my code is ok. Can you please check it?
Problem:
I want to include all my Java files from all my projects (created with Netbeans), the projects are stored in one folder, into a LaTeX document. I solved it with this code:
package dir;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Dir {
private static String fileType;
private static String fileName;
private static String pathName;
private static String folderName;
private static String oldFolderName = "";
public static void main(String[] args) {
File currentDir = new File(".");
content(currentDir);
}
public static void content(File dir) {
try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
pathName = file.getName();
if (pathName.equals("src")) {
pathName = "main";
}
content(file);
} else {
fileType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
if (fileType.equals("text/x-java")) {
fileName = file.getName();
folderName = file.getParentFile().getName();
if(folderName.equals("src")){
folderName = file.getParentFile().getParentFile().getName();
}else{
folderName = file.getParentFile().getParentFile().getParentFile().getName();
}
if(!folderName.equals(oldFolderName)){
System.out.println("\\section{" + folderName + "}");
}
if(!pathName.equals("")){
System.out.println("\\subsection{" + pathName + "}");
}
System.out.println("\\subsubsection{" + fileName + "}");
System.out.println("\\lstinputlisting[language=java]{" + file.getCanonicalPath() + "}");
System.out.println("");
pathName = "";
oldFolderName = folderName;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am especially frustrated about following part:
if(folderName.equals("src")){
folderName = file.getParentFile().getParentFile().getName();
}else{
folderName = file.getParentFile().getParentFile().getParentFile().getName();
}
Is there a better way to loop through all the .getParentFile()
until you get the .getParentFile().getName()
of the folder named "src"?
Furthermore one question: my code doesn't iterate sorted through my folders and files. I mean, if the subfolder of the folder I am in are like 3, 4, 5 and 6, the code just don't open folder 3 first, but just chooses a random file. It would be nice if you could help me to fix it.