You need a library that can read the file and tell you the length. For example, using Caprica's VLCJ, which wraps VLC, once you point a MediaPlayer
to your file, you can ask it for its length in seconds. I am not sure whether this will work without an interface, though.
Another option is Xuggler, which wraps FFMPEG. There, you can write the following to open a file and ask for its duration:
IMediaReader reader = ToolFactory.makeReader(filename);
IContainer container = reader.getContainer();
if (container.queryStreamMetaData() >= 0) {
long duration = container.getDuration(); // <-- got it
}
Note that there is a lot of variability in what you can expect from an .mp4 file (mp4 is a container, not an encoding) - so beware malformed or unsupported variants.
Both VLCJ and Xuggler are GPLv3; you may need to isolate your program from them as plugins unless your code will also be GPL'd, depending on how you interpret java linking.
Another option is to call a system script that provides you the number. This dispenses with Java integration, but forces you to keep the script updated and have its system dependency available. For ubuntu linux, these can work:
ffprobe file.mp4 -show_format_entry duration
or
avprobe file.mp4 -show_format_entry duration
or
$ mediainfo --Inform="Video;%Duration%" [inputfile]
all of them found in this answer