From 8021dd76afba1f5e2bdb2778587f4de5e1a2c0f4 Mon Sep 17 00:00:00 2001 From: Piotr Findeisen Date: Fri, 31 Dec 2021 18:37:01 +0100 Subject: [PATCH] Use SerialPort with try-with-resources Let the `SerialPort` implement `AutoCloseable`. This requires bumping minimal required Java version to 7. --- build.gradle | 4 ++-- src/main/java/com/fazecast/jSerialComm/SerialPort.java | 10 +++++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/build.gradle b/build.gradle index fcb66f30..716f4773 100644 --- a/build.gradle +++ b/build.gradle @@ -21,8 +21,8 @@ if (hasProperty('manualBuild')) assert hasProperty('java9Home'): "Set the property 'java9Home' in your gradle.properties file pointing to a Java 9 JDK installation" } -sourceCompatibility = 1.6 -targetCompatibility = 1.6 +sourceCompatibility = 1.7 +targetCompatibility = 1.7 javadoc.options.links("https://docs.oracle.com/javase/9/docs/api/") javadoc.options.addBooleanOption('html4', true) diff --git a/src/main/java/com/fazecast/jSerialComm/SerialPort.java b/src/main/java/com/fazecast/jSerialComm/SerialPort.java index 97a8d9ee..663c3c6d 100644 --- a/src/main/java/com/fazecast/jSerialComm/SerialPort.java +++ b/src/main/java/com/fazecast/jSerialComm/SerialPort.java @@ -47,7 +47,7 @@ * @see java.io.InputStream * @see java.io.OutputStream */ -public final class SerialPort +public final class SerialPort implements AutoCloseable { // Static initializer loads correct native library for this machine static private final String versionString = "2.8.0"; @@ -617,6 +617,14 @@ public final synchronized boolean closePort() } } + @Override + public void close() throws SerialPortIOException + { + if (!closePort()) { + throw new SerialPortIOException("Failed to close"); + } + } + /** * Returns whether the port is currently open and available for communication. *