package chuankou; import java.io.File; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; /** * Ensures the correct jSerialComm native library is available on Windows/x86_64 systems. */ public final class SerialPortNativeLoader { private static final String LIB_PROPERTY = "com.fazecast.jSerialComm.library.path"; private static final String EXPECTED_DLL = "jSerialComm.dll"; private SerialPortNativeLoader() { // utility class } public static void ensureLibraryPresent() { if (System.getProperty(LIB_PROPERTY) != null) { return; } String osName = System.getProperty("os.name", "").toLowerCase(); if (!osName.contains("win")) { return; } String arch = System.getProperty("os.arch", "").toLowerCase(); if (!arch.contains("64")) { return; } Path candidateDir = Paths.get("lib", "native", "windows", "x86_64").toAbsolutePath(); File dllFile = candidateDir.resolve(EXPECTED_DLL).toFile(); if (!dllFile.isFile()) { candidateDir = resolveFromCodeSource(); if (candidateDir != null) { dllFile = candidateDir.resolve(EXPECTED_DLL).toFile(); } } if (dllFile.isFile()) { System.setProperty(LIB_PROPERTY, candidateDir.toString()); } else { System.err.println("Expected jSerialComm native library not found. Checked " + dllFile); } } private static Path resolveFromCodeSource() { try { java.security.CodeSource codeSource = SerialPortNativeLoader.class.getProtectionDomain().getCodeSource(); if (codeSource == null) { return null; } Path location = Paths.get(codeSource.getLocation().toURI()).toAbsolutePath(); Path baseDir = location.getParent(); if (baseDir == null) { return null; } Path siblingLibDir = baseDir.resolveSibling("lib").resolve("native").resolve("windows").resolve("x86_64"); if (siblingLibDir.toFile().isDirectory()) { return siblingLibDir; } Path relativeLibDir = baseDir.resolve("lib").resolve("native").resolve("windows").resolve("x86_64"); if (relativeLibDir.toFile().isDirectory()) { return relativeLibDir; } } catch (URISyntaxException | SecurityException ignored) { // ignore } return null; } }