8274893: Update java.desktop classes to use try-with-resources

Reviewed-by: serb
This commit is contained in:
Andrey Turbanov 2021-12-24 02:02:39 +00:00 committed by Sergey Bylokhov
parent d52392c15e
commit 70c6df6be4
24 changed files with 129 additions and 200 deletions

@ -669,18 +669,9 @@ public class PNGImageReader extends ImageReader {
private static byte[] inflate(byte[] b) throws IOException {
InputStream bais = new ByteArrayInputStream(b);
InputStream iis = new InflaterInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
try {
while ((c = iis.read()) != -1) {
baos.write(c);
}
} finally {
iis.close();
try (InputStream iis = new InflaterInputStream(bais)) {
return iis.readAllBytes();
}
return baos.toByteArray();
}
private void parse_zTXt_chunk(int chunkLength) throws IOException {

@ -583,15 +583,16 @@ class Metacity implements SynthConstants {
URL url = new URL(new File(userHome).toURI().toURL(),
".gconf/apps/metacity/general/%25gconf.xml");
// Pending: verify character encoding spec for gconf
Reader reader = new InputStreamReader(url.openStream(),
ISO_8859_1);
char[] buf = new char[1024];
StringBuilder sb = new StringBuilder();
int n;
while ((n = reader.read(buf)) >= 0) {
sb.append(buf, 0, n);
try (InputStream in = url.openStream();
Reader reader = new InputStreamReader(in, ISO_8859_1))
{
char[] buf = new char[1024];
int n;
while ((n = reader.read(buf)) >= 0) {
sb.append(buf, 0, n);
}
}
reader.close();
String str = sb.toString();
if (str != null) {
String strLowerCase = str.toLowerCase();

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -48,10 +48,8 @@ public final class AudioFileSoundbankReader extends SoundbankReader {
@Override
public Soundbank getSoundbank(URL url)
throws InvalidMidiDataException, IOException {
try {
AudioInputStream ais = AudioSystem.getAudioInputStream(url);
try (AudioInputStream ais = AudioSystem.getAudioInputStream(url)) {
Soundbank sbk = getSoundbank(ais);
ais.close();
return sbk;
} catch (UnsupportedAudioFileException e) {
return null;

@ -191,22 +191,16 @@ public final class DLSSoundbank implements Soundbank {
}
public DLSSoundbank(URL url) throws IOException {
InputStream is = url.openStream();
try {
try (InputStream is = url.openStream()) {
readSoundbank(is);
} finally {
is.close();
}
}
public DLSSoundbank(File file) throws IOException {
largeFormat = true;
sampleFile = file;
InputStream is = new FileInputStream(file);
try {
try (InputStream is = new FileInputStream(file)) {
readSoundbank(is);
} finally {
is.close();
}
}
@ -875,15 +869,21 @@ public final class DLSSoundbank implements Soundbank {
}
public void save(String name) throws IOException {
writeSoundbank(new RIFFWriter(name, "DLS "));
try (RIFFWriter writer = new RIFFWriter(name, "DLS ")) {
writeSoundbank(writer);
}
}
public void save(File file) throws IOException {
writeSoundbank(new RIFFWriter(file, "DLS "));
try (RIFFWriter writer = new RIFFWriter(file, "DLS ")) {
writeSoundbank(writer);
}
}
public void save(OutputStream out) throws IOException {
writeSoundbank(new RIFFWriter(out, "DLS "));
try (RIFFWriter writer = new RIFFWriter(out, "DLS ")) {
writeSoundbank(writer);
}
}
private void writeSoundbank(RIFFWriter writer) throws IOException {
@ -923,8 +923,6 @@ public final class DLSSoundbank implements Soundbank {
writer.seek(bak);
writeInfo(writer.writeList("INFO"), info);
writer.close();
}
private void writeSample(RIFFWriter writer, DLSSample sample)

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -51,8 +51,7 @@ public final class JARSoundbankReader extends SoundbankReader {
private static boolean isZIP(URL url) {
boolean ok = false;
try {
InputStream stream = url.openStream();
try {
try (InputStream stream = url.openStream()) {
byte[] buff = new byte[4];
ok = stream.read(buff) == 4;
if (ok) {
@ -61,8 +60,6 @@ public final class JARSoundbankReader extends SoundbankReader {
&& buff[2] == 0x03
&& buff[3] == 0x04);
}
} finally {
stream.close();
}
} catch (IOException e) {
}
@ -81,8 +78,7 @@ public final class JARSoundbankReader extends SoundbankReader {
"META-INF/services/javax.sound.midi.Soundbank");
if (stream == null)
return null;
try
{
try (stream) {
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
String line = r.readLine();
while (line != null) {
@ -100,10 +96,6 @@ public final class JARSoundbankReader extends SoundbankReader {
line = r.readLine();
}
}
finally
{
stream.close();
}
if (soundbanks.size() == 0)
return null;
if (soundbanks.size() == 1)

@ -315,11 +315,13 @@ public final class ModelByteBuffer {
"No file associated with this ByteBuffer!");
}
DataInputStream is = new DataInputStream(getInputStream());
buffer = new byte[(int) capacity()];
offset = 0;
is.readFully(buffer);
is.close();
try (InputStream is = getInputStream();
DataInputStream dis = new DataInputStream(is))
{
buffer = new byte[(int) capacity()];
offset = 0;
dis.readFully(buffer);
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -182,18 +182,12 @@ public final class ModelByteBufferWavetable implements ModelWavetable {
if (format == null) {
if (buffer == null)
return null;
InputStream is = buffer.getInputStream();
AudioFormat format = null;
try {
try (InputStream is = buffer.getInputStream()) {
format = AudioSystem.getAudioFileFormat(is).getFormat();
} catch (Exception e) {
//e.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
//e.printStackTrace();
}
return format;
}
return format;

@ -92,23 +92,16 @@ public final class SF2Soundbank implements Soundbank {
}
public SF2Soundbank(URL url) throws IOException {
InputStream is = url.openStream();
try {
try (InputStream is = url.openStream()) {
readSoundbank(is);
} finally {
is.close();
}
}
public SF2Soundbank(File file) throws IOException {
largeFormat = true;
sampleFile = file;
InputStream is = new FileInputStream(file);
try {
try (InputStream is = new FileInputStream(file)) {
readSoundbank(is);
} finally {
is.close();
}
}
@ -517,22 +510,27 @@ public final class SF2Soundbank implements Soundbank {
}
public void save(String name) throws IOException {
writeSoundbank(new RIFFWriter(name, "sfbk"));
try (RIFFWriter writer = new RIFFWriter(name, "sfbk")) {
writeSoundbank(writer);
}
}
public void save(File file) throws IOException {
writeSoundbank(new RIFFWriter(file, "sfbk"));
try (RIFFWriter writer = new RIFFWriter(file, "sfbk")) {
writeSoundbank(writer);
}
}
public void save(OutputStream out) throws IOException {
writeSoundbank(new RIFFWriter(out, "sfbk"));
try (RIFFWriter writer = new RIFFWriter(out, "sfbk")) {
writeSoundbank(writer);
}
}
private void writeSoundbank(RIFFWriter writer) throws IOException {
writeInfo(writer.writeList("INFO"));
writeSdtaChunk(writer.writeList("sdta"));
writePdtaChunk(writer.writeList("pdta"));
writer.close();
}
private void writeInfoStringChunk(RIFFWriter writer, String name,

@ -755,10 +755,8 @@ public final class SoftSynthesizer implements AudioSynthesizer,
InputStream is = AccessController.doPrivileged(action);
if(is == null) continue;
Soundbank sbk;
try {
try (is) {
sbk = MidiSystem.getSoundbank(new BufferedInputStream(is));
} finally {
is.close();
}
if (sbk != null) {
defaultSoundBank = sbk;
@ -802,9 +800,8 @@ public final class SoftSynthesizer implements AudioSynthesizer,
return null;
});
if (out != null) {
try {
try (out) {
((SF2Soundbank) defaultSoundBank).save(out);
out.close();
} catch (final IOException ignored) {
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -146,34 +146,27 @@ public final class StandardMidiFileReader extends MidiFileReader {
@Override
public MidiFileFormat getMidiFileFormat(URL url) throws InvalidMidiDataException, IOException {
InputStream urlStream = url.openStream(); // throws IOException
BufferedInputStream bis = new BufferedInputStream( urlStream, bisBufferSize );
MidiFileFormat fileFormat = null;
try {
fileFormat = getMidiFileFormat( bis ); // throws InvalidMidiDataException
} finally {
bis.close();
try (InputStream urlStream = url.openStream(); // throws IOException
BufferedInputStream bis = new BufferedInputStream(urlStream, bisBufferSize))
{
MidiFileFormat fileFormat = getMidiFileFormat(bis); // throws InvalidMidiDataException
return fileFormat;
}
return fileFormat;
}
@Override
public MidiFileFormat getMidiFileFormat(File file) throws InvalidMidiDataException, IOException {
FileInputStream fis = new FileInputStream(file); // throws IOException
BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize);
// $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length
long length = file.length();
if (length > Integer.MAX_VALUE) {
length = MidiFileFormat.UNKNOWN_LENGTH;
try (FileInputStream fis = new FileInputStream(file); // throws IOException
BufferedInputStream bis = new BufferedInputStream(fis, bisBufferSize))
{
// $$fb 2002-04-17: part of fix for 4635286: MidiSystem.getMidiFileFormat() returns format having invalid length
long length = file.length();
if (length > Integer.MAX_VALUE) {
length = MidiFileFormat.UNKNOWN_LENGTH;
}
MidiFileFormat fileFormat = getMidiFileFormatFromStream(bis, (int) length, null);
return fileFormat;
}
MidiFileFormat fileFormat = null;
try {
fileFormat = getMidiFileFormatFromStream(bis, (int) length, null);
} finally {
bis.close();
}
return fileFormat;
}
@Override
@ -204,28 +197,22 @@ public final class StandardMidiFileReader extends MidiFileReader {
@Override
public Sequence getSequence(URL url) throws InvalidMidiDataException, IOException {
InputStream is = url.openStream(); // throws IOException
is = new BufferedInputStream(is, bisBufferSize);
Sequence seq = null;
try {
seq = getSequence(is);
} finally {
is.close();
try (InputStream is = url.openStream(); // throws IOException
BufferedInputStream bis = new BufferedInputStream(is, bisBufferSize))
{
Sequence seq = getSequence(bis);
return seq;
}
return seq;
}
@Override
public Sequence getSequence(File file) throws InvalidMidiDataException, IOException {
InputStream is = new FileInputStream(file); // throws IOException
is = new BufferedInputStream(is, bisBufferSize);
Sequence seq = null;
try {
seq = getSequence(is);
} finally {
is.close();
try (InputStream is = new FileInputStream(file); // throws IOException
BufferedInputStream bis = new BufferedInputStream(is, bisBufferSize))
{
Sequence seq = getSequence(bis);
return seq;
}
return seq;
}
}

@ -129,10 +129,10 @@ public final class StandardMidiFileWriter extends MidiFileWriter {
@Override
public int write(Sequence in, int type, File out) throws IOException {
Objects.requireNonNull(in);
FileOutputStream fos = new FileOutputStream(out); // throws IOException
int bytesWritten = write( in, type, fos );
fos.close();
return bytesWritten;
try (FileOutputStream fos = new FileOutputStream(out)) { // throws IOException
int bytesWritten = write(in, type, fos);
return bytesWritten;
}
}
//=================================================================================

@ -1131,7 +1131,7 @@ public class Font implements java.io.Serializable
if (tracker != null) {
tracker.set(tFile, outStream);
}
try {
try (outStream) { /* don't close the input stream */
byte[] buf = new byte[8192];
for (;;) {
int bytesRead = fontStream.read(buf);
@ -1152,9 +1152,6 @@ public class Font implements java.io.Serializable
}
outStream.write(buf, 0, bytesRead);
}
/* don't close the input stream */
} finally {
outStream.close();
}
/* After all references to a Font2D are dropped, the file
* will be removed. To support long-lived AppContexts,

@ -413,12 +413,10 @@ public abstract class Toolkit {
File propsFile = new File(
System.getProperty("user.home") +
sep + ".accessibility.properties");
FileInputStream in =
new FileInputStream(propsFile);
// Inputstream has been buffered in Properties class
properties.load(in);
in.close();
try (FileInputStream in = new FileInputStream(propsFile)) {
// Inputstream has been buffered in Properties class
properties.load(in);
}
} catch (Exception e) {
// Per-user accessibility properties file does not exist
}
@ -431,12 +429,10 @@ public abstract class Toolkit {
File propsFile = new File(
System.getProperty("java.home") + sep + "conf" +
sep + "accessibility.properties");
FileInputStream in =
new FileInputStream(propsFile);
// Inputstream has been buffered in Properties class
properties.load(in);
in.close();
try (FileInputStream in = new FileInputStream(propsFile)) {
// Inputstream has been buffered in Properties class
properties.load(in);
}
} catch (Exception e) {
// System-wide accessibility properties file does
// not exist;

@ -201,7 +201,7 @@ public class Beans {
else
ins = cls.getResourceAsStream(serName);
if (ins != null) {
try {
try (ins) {
if (cls == null) {
oins = new ObjectInputStream(ins);
} else {
@ -211,13 +211,9 @@ public class Beans {
serialized = true;
oins.close();
} catch (IOException ex) {
ins.close();
// Drop through and try opening the class. But remember
// the exception in case we can't find the class either.
serex = ex;
} catch (ClassNotFoundException ex) {
ins.close();
throw ex;
}
}

@ -39,8 +39,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.spi.ImageReaderWriterSpi;
@ -1402,7 +1400,7 @@ public final class ImageIO {
throw new IllegalArgumentException("input == null!");
}
InputStream istream = null;
InputStream istream;
try {
istream = input.openStream();
} catch (IOException e) {
@ -1418,13 +1416,11 @@ public final class ImageIO {
throw new IIOException("Can't create an ImageInputStream!");
}
BufferedImage bi;
try {
try (istream) {
bi = read(stream);
if (bi == null) {
stream.close();
}
} finally {
istream.close();
}
return bi;
}
@ -1466,11 +1462,10 @@ public final class ImageIO {
ImageReadParam param = reader.getDefaultReadParam();
reader.setInput(stream, true, true);
BufferedImage bi;
try {
try (stream) {
bi = reader.read(0, param);
} finally {
reader.dispose();
stream.close();
}
return bi;
}
@ -1552,10 +1547,8 @@ public final class ImageIO {
if (stream == null) {
throw new IIOException("Can't create an ImageOutputStream!");
}
try {
try (stream) {
return doWrite(im, writer, stream);
} finally {
stream.close();
}
}
@ -1592,10 +1585,8 @@ public final class ImageIO {
if (stream == null) {
throw new IIOException("Can't create an ImageOutputStream!");
}
try {
try (stream) {
return doWrite(im, getWriter(im, formatName), stream);
} finally {
stream.close();
}
}

@ -41,6 +41,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serial;
import java.io.StringReader;
@ -852,16 +853,12 @@ public class JEditorPane extends JTextComponent {
private void handlePostData(HttpURLConnection conn, Object postData)
throws IOException {
conn.setDoOutput(true);
DataOutputStream os = null;
try {
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
os = new DataOutputStream(conn.getOutputStream());
os.writeBytes((String) postData);
} finally {
if (os != null) {
os.close();
}
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
try (OutputStream os = conn.getOutputStream();
DataOutputStream dos = new DataOutputStream(os))
{
dos.writeBytes((String)postData);
}
}

@ -57,7 +57,6 @@ import sun.awt.SunToolkit;
import sun.awt.OSInfo;
import sun.security.action.GetPropertyAction;
import sun.swing.SwingUtilities2;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Objects;
import sun.awt.AppContext;
@ -1301,9 +1300,9 @@ public class UIManager implements Serializable
if (file.exists()) {
// InputStream has been buffered in Properties
// class
FileInputStream ins = new FileInputStream(file);
props.load(ins);
ins.close();
try (FileInputStream ins = new FileInputStream(file)) {
props.load(ins);
}
}
}
catch (Exception e) {

@ -456,12 +456,11 @@ public class HTMLEditorKit extends StyledEditorKit implements Accessible {
if (defaultStyles == null) {
defaultStyles = new StyleSheet();
appContext.put(DEFAULT_STYLES_KEY, defaultStyles);
try {
InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS);
Reader r = new BufferedReader(
new InputStreamReader(is, ISO_8859_1));
try (InputStream is = HTMLEditorKit.getResourceAsStream(DEFAULT_CSS);
InputStreamReader isr = new InputStreamReader(is, ISO_8859_1);
Reader r = new BufferedReader(isr))
{
defaultStyles.loadRules(r, null);
r.close();
} catch (Throwable e) {
// on error we simply have no styles... the html
// will look mighty wrong but still function.

@ -478,15 +478,12 @@ public class StyleSheet extends StyleContext {
* @since 1.3
*/
public void importStyleSheet(URL url) {
try {
InputStream is;
is = url.openStream();
Reader r = new BufferedReader(new InputStreamReader(is));
try (InputStream is = url.openStream();
InputStreamReader isr = new InputStreamReader(is);
Reader r = new BufferedReader(isr))
{
CssParser parser = new CssParser();
parser.parse(url, r, false, true);
r.close();
is.close();
} catch (Throwable e) {
// on error we simply have no styles... the html
// will look mighty wrong but still function.

@ -173,9 +173,9 @@ public final class DebugSettings {
File propFile = new File(propPath);
try {
println("Reading debug settings from '" + propFile.getCanonicalPath() + "'...");
FileInputStream fin = new FileInputStream(propFile);
props.load(fin);
fin.close();
try (FileInputStream fin = new FileInputStream(propFile)) {
props.load(fin);
}
} catch ( FileNotFoundException fne ) {
println("Did not find settings file.");
} catch ( IOException ioe ) {

@ -48,7 +48,6 @@ import java.util.Set;
import java.util.Vector;
import sun.font.CompositeFontDescriptor;
import sun.font.SunFontManager;
import sun.font.FontManagerFactory;
import sun.font.FontUtilities;
import sun.util.logging.PlatformLogger;
@ -204,14 +203,12 @@ public abstract class FontConfiguration {
getInstalledFallbackFonts(javaLib);
if (f != null) {
try {
FileInputStream in = new FileInputStream(f.getPath());
try (FileInputStream in = new FileInputStream(f.getPath())) {
if (isProperties) {
loadProperties(in);
} else {
loadBinary(in);
}
in.close();
if (FontUtilities.debugFonts()) {
logger.config("Read logical font configuration from " + f);
}

@ -393,11 +393,12 @@ public class PSPrinterJob extends RasterPrinterJob {
}
// Load property file
InputStream in =
new BufferedInputStream(new FileInputStream(f.getPath()));
Properties props = new Properties();
props.load(in);
in.close();
try (FileInputStream is = new FileInputStream(f.getPath());
BufferedInputStream bis = new BufferedInputStream(is))
{
props.load(bis);
}
return props;
} catch (Exception e){
return (Properties)null;

@ -314,7 +314,9 @@ public class FcFontConfiguration extends FontConfiguration {
* For Ubuntu the ID is "Ubuntu".
*/
Properties props = new Properties();
props.load(new FileInputStream(f));
try (FileInputStream fis = new FileInputStream(f)) {
props.load(fis);
}
osName = props.getProperty("DISTRIB_ID");
osVersion = props.getProperty("DISTRIB_RELEASE");
} else if ((f = new File("/etc/redhat-release")).canRead()) {
@ -401,10 +403,9 @@ public class FcFontConfiguration extends FontConfiguration {
File dir = fcInfoFile.getParentFile();
dir.mkdirs();
File tempFile = Files.createTempFile(dir.toPath(), "fcinfo", null).toFile();
FileOutputStream fos = new FileOutputStream(tempFile);
props.store(fos,
"JDK Font Configuration Generated File: *Do Not Edit*");
fos.close();
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
props.store(fos, "JDK Font Configuration Generated File: *Do Not Edit*");
}
boolean renamed = tempFile.renameTo(fcInfoFile);
if (!renamed && FontUtilities.debugFonts()) {
System.out.println("rename failed");

@ -27,8 +27,6 @@ package sun.font;
import sun.awt.FontConfiguration;
import sun.awt.X11FontManager;
import sun.font.FontUtilities;
import sun.font.SunFontManager;
import sun.util.logging.PlatformLogger;
import java.io.File;
@ -111,7 +109,9 @@ public class MFontConfiguration extends FontConfiguration {
* For Ubuntu the ID is "Ubuntu".
*/
Properties props = new Properties();
props.load(new FileInputStream(f));
try (FileInputStream fis = new FileInputStream(f)) {
props.load(fis);
}
osName = props.getProperty("DISTRIB_ID");
osVersion = props.getProperty("DISTRIB_RELEASE");
}