// Independent developer-only Apache POI5.4.1 source reading, never in the app.
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFAbstractFootnoteEndnote;
public class WordNoteSourceReader {
 public static void main(String[] args)throws Exception{
  Path source=Path.of(args[0]),out=Path.of(args[1]);Files.createDirectories(out);
  if(source.toString().endsWith(".doc")){
   try(var reader=new WordExtractor(Files.newInputStream(source))){
    Files.writeString(out.resolve("body.txt"),String.join("",reader.getParagraphText()),StandardCharsets.UTF_8);
    Files.writeString(out.resolve("footnotes.txt"),String.join("\n",reader.getFootnoteText()),StandardCharsets.UTF_8);
    Files.writeString(out.resolve("endnotes.txt"),String.join("\n",reader.getEndnoteText()),StandardCharsets.UTF_8);
   }
  }else{
   try(var doc=new XWPFDocument(Files.newInputStream(source))){
    StringBuilder footnotes=new StringBuilder(),endnotes=new StringBuilder();
    for(var note:doc.getFootnotes())append(footnotes,note);
    for(var note:doc.getEndnotes())append(endnotes,note);
    Files.writeString(out.resolve("footnotes.txt"),footnotes,StandardCharsets.UTF_8);
    Files.writeString(out.resolve("endnotes.txt"),endnotes,StandardCharsets.UTF_8);
   }
  }
 }
 private static void append(StringBuilder result,XWPFAbstractFootnoteEndnote note){
  result.append("[Source ID ").append(note.getId()).append("]\n");
  for(var paragraph:note.getParagraphs())result.append(paragraph.getText()).append("\n");
 }
}
