提交 f0cd7ae8 编写于 作者: S Stephen Connolly

[JENKINS-42934] Avoid using new FileInputStream / new FileOutputStream

上级 4948d6c5
...@@ -30,6 +30,8 @@ import java.io.DataInputStream; ...@@ -30,6 +30,8 @@ import java.io.DataInputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.KeyPair; import java.security.KeyPair;
...@@ -127,7 +129,7 @@ public class PrivateKeyProvider { ...@@ -127,7 +129,7 @@ public class PrivateKeyProvider {
} }
private static String readPemFile(File f) throws IOException{ private static String readPemFile(File f) throws IOException{
try (FileInputStream is = new FileInputStream(f); try (InputStream is = Files.newInputStream(f.toPath());
DataInputStream dis = new DataInputStream(is)) { DataInputStream dis = new DataInputStream(is)) {
byte[] bytes = new byte[(int) f.length()]; byte[] bytes = new byte[(int) f.length()];
dis.readFully(bytes); dis.readFully(bytes);
......
...@@ -23,6 +23,8 @@ ...@@ -23,6 +23,8 @@
*/ */
package hudson; package hudson;
import java.io.InputStream;
import java.nio.file.Files;
import jenkins.util.SystemProperties; import jenkins.util.SystemProperties;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import hudson.Plugin.DummyImpl; import hudson.Plugin.DummyImpl;
...@@ -123,11 +125,8 @@ public class ClassicPluginStrategy implements PluginStrategy { ...@@ -123,11 +125,8 @@ public class ClassicPluginStrategy implements PluginStrategy {
try { try {
// Locate the manifest // Locate the manifest
String firstLine; String firstLine;
FileInputStream manifestHeaderInput = new FileInputStream(archive); try (InputStream manifestHeaderInput = Files.newInputStream(archive.toPath())) {
try {
firstLine = IOUtils.readFirstLine(manifestHeaderInput, "UTF-8"); firstLine = IOUtils.readFirstLine(manifestHeaderInput, "UTF-8");
} finally {
manifestHeaderInput.close();
} }
if (firstLine.startsWith("Manifest-Version:")) { if (firstLine.startsWith("Manifest-Version:")) {
// this is the manifest already // this is the manifest already
...@@ -137,11 +136,8 @@ public class ClassicPluginStrategy implements PluginStrategy { ...@@ -137,11 +136,8 @@ public class ClassicPluginStrategy implements PluginStrategy {
} }
// Read the manifest // Read the manifest
FileInputStream manifestInput = new FileInputStream(archive); try (InputStream manifestInput = Files.newInputStream(archive.toPath())) {
try {
return new Manifest(manifestInput); return new Manifest(manifestInput);
} finally {
manifestInput.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new IOException("Failed to load " + archive, e); throw new IOException("Failed to load " + archive, e);
...@@ -173,7 +169,7 @@ public class ClassicPluginStrategy implements PluginStrategy { ...@@ -173,7 +169,7 @@ public class ClassicPluginStrategy implements PluginStrategy {
"Plugin installation failed. No manifest at " "Plugin installation failed. No manifest at "
+ manifestFile); + manifestFile);
} }
try (FileInputStream fin = new FileInputStream(manifestFile)) { try (InputStream fin = Files.newInputStream(manifestFile.toPath())) {
manifest = new Manifest(fin); manifest = new Manifest(fin);
} }
} }
......
...@@ -25,7 +25,6 @@ ...@@ -25,7 +25,6 @@
*/ */
package hudson; package hudson;
import jenkins.util.SystemProperties;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.jcraft.jzlib.GZIPInputStream; import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream; import com.jcraft.jzlib.GZIPOutputStream;
...@@ -59,29 +58,9 @@ import hudson.util.IOUtils; ...@@ -59,29 +58,9 @@ import hudson.util.IOUtils;
import hudson.util.NamingThreadFactory; import hudson.util.NamingThreadFactory;
import hudson.util.io.Archiver; import hudson.util.io.Archiver;
import hudson.util.io.ArchiverFactory; import hudson.util.io.ArchiverFactory;
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.SoloFilePathFilter;
import jenkins.model.Jenkins;
import jenkins.util.ContextResettingExecutorService;
import jenkins.util.VirtualFile;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
import javax.annotation.CheckForNull;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
...@@ -99,6 +78,7 @@ import java.net.MalformedURLException; ...@@ -99,6 +78,7 @@ import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
...@@ -116,16 +96,37 @@ import java.util.logging.Level; ...@@ -116,16 +96,37 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.annotation.CheckForNull;
import static hudson.FilePath.TarCompression.*;
import static hudson.Util.*;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import jenkins.FilePathFilter;
import jenkins.MasterToSlaveFileCallable;
import jenkins.SlaveToMasterFileCallable;
import jenkins.SoloFilePathFilter;
import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable; import jenkins.security.MasterToSlaveCallable;
import jenkins.util.ContextResettingExecutorService;
import jenkins.util.SystemProperties;
import jenkins.util.VirtualFile;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.input.CountingInputStream;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.jenkinsci.remoting.RoleChecker; import org.jenkinsci.remoting.RoleChecker;
import org.jenkinsci.remoting.RoleSensitive; import org.jenkinsci.remoting.RoleSensitive;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
import static hudson.FilePath.TarCompression.GZIP;
import static hudson.Util.deleteFile;
import static hudson.Util.fixEmpty;
import static hudson.Util.isSymlink;
/** /**
* {@link File} like object with remoting support. * {@link File} like object with remoting support.
...@@ -1470,7 +1471,7 @@ public final class FilePath implements Serializable { ...@@ -1470,7 +1471,7 @@ public final class FilePath implements Serializable {
private static final long serialVersionUID = -5094638816500738429L; private static final long serialVersionUID = -5094638816500738429L;
public Void invoke(File f, VirtualChannel channel) throws IOException { public Void invoke(File f, VirtualChannel channel) throws IOException {
if(!f.exists()) if(!f.exists())
new FileOutputStream(creating(f)).close(); Files.newOutputStream(creating(f).toPath()).close();
if(!stating(f).setLastModified(timestamp)) if(!stating(f).setLastModified(timestamp))
throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp); throw new IOException("Failed to set the timestamp of "+f+" to "+timestamp);
return null; return null;
...@@ -1751,7 +1752,7 @@ public final class FilePath implements Serializable { ...@@ -1751,7 +1752,7 @@ public final class FilePath implements Serializable {
*/ */
public InputStream read() throws IOException, InterruptedException { public InputStream read() throws IOException, InterruptedException {
if(channel==null) if(channel==null)
return new FileInputStream(reading(new File(remote))); return Files.newInputStream(reading(new File(remote)).toPath());
final Pipe p = Pipe.createRemoteToLocal(); final Pipe p = Pipe.createRemoteToLocal();
actAsync(new SecureFileCallable<Void>() { actAsync(new SecureFileCallable<Void>() {
...@@ -1759,9 +1760,9 @@ public final class FilePath implements Serializable { ...@@ -1759,9 +1760,9 @@ public final class FilePath implements Serializable {
@Override @Override
public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { public Void invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
FileInputStream fis = null; InputStream fis = null;
try { try {
fis = new FileInputStream(reading(f)); fis = Files.newInputStream(reading(f).toPath());
Util.copyStream(fis, p.getOut()); Util.copyStream(fis, p.getOut());
} catch (Exception x) { } catch (Exception x) {
p.error(x); p.error(x);
...@@ -1876,7 +1877,7 @@ public final class FilePath implements Serializable { ...@@ -1876,7 +1877,7 @@ public final class FilePath implements Serializable {
if(channel==null) { if(channel==null) {
File f = new File(remote).getAbsoluteFile(); File f = new File(remote).getAbsoluteFile();
mkdirs(f.getParentFile()); mkdirs(f.getParentFile());
return new FileOutputStream(writing(f)); return Files.newOutputStream(writing(f).toPath());
} }
return act(new SecureFileCallable<OutputStream>() { return act(new SecureFileCallable<OutputStream>() {
...@@ -1884,7 +1885,7 @@ public final class FilePath implements Serializable { ...@@ -1884,7 +1885,7 @@ public final class FilePath implements Serializable {
public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException { public OutputStream invoke(File f, VirtualChannel channel) throws IOException, InterruptedException {
f = f.getAbsoluteFile(); f = f.getAbsoluteFile();
mkdirs(f.getParentFile()); mkdirs(f.getParentFile());
FileOutputStream fos = new FileOutputStream(writing(f)); OutputStream fos = Files.newOutputStream(writing(f).toPath());
return new RemoteOutputStream(fos); return new RemoteOutputStream(fos);
} }
}); });
...@@ -1902,8 +1903,8 @@ public final class FilePath implements Serializable { ...@@ -1902,8 +1903,8 @@ public final class FilePath implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public Void invoke(File f, VirtualChannel channel) throws IOException { public Void invoke(File f, VirtualChannel channel) throws IOException {
mkdirs(f.getParentFile()); mkdirs(f.getParentFile());
FileOutputStream fos = new FileOutputStream(writing(f)); try (OutputStream fos = Files.newOutputStream(writing(f).toPath());
try (Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) { Writer w = encoding != null ? new OutputStreamWriter(fos, encoding) : new OutputStreamWriter(fos)) {
w.write(content); w.write(content);
} }
return null; return null;
...@@ -2005,9 +2006,9 @@ public final class FilePath implements Serializable { ...@@ -2005,9 +2006,9 @@ public final class FilePath implements Serializable {
act(new SecureFileCallable<Void>() { act(new SecureFileCallable<Void>() {
private static final long serialVersionUID = 4088559042349254141L; private static final long serialVersionUID = 4088559042349254141L;
public Void invoke(File f, VirtualChannel channel) throws IOException { public Void invoke(File f, VirtualChannel channel) throws IOException {
FileInputStream fis = null; InputStream fis = null;
try { try {
fis = new FileInputStream(reading(f)); fis = Files.newInputStream(reading(f).toPath());
Util.copyStream(fis,out); Util.copyStream(fis,out);
return null; return null;
} finally { } finally {
......
...@@ -31,6 +31,7 @@ import hudson.model.Describable; ...@@ -31,6 +31,7 @@ import hudson.model.Describable;
import hudson.model.Job; import hudson.model.Job;
import hudson.model.TaskListener; import hudson.model.TaskListener;
import hudson.util.io.ArchiverFactory; import hudson.util.io.ArchiverFactory;
import java.nio.file.Files;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import hudson.model.listeners.RunListener; import hudson.model.listeners.RunListener;
import hudson.scm.SCM; import hudson.scm.SCM;
...@@ -215,7 +216,7 @@ public abstract class FileSystemProvisioner implements ExtensionPoint, Describab ...@@ -215,7 +216,7 @@ public abstract class FileSystemProvisioner implements ExtensionPoint, Describab
*/ */
public WorkspaceSnapshot snapshot(AbstractBuild<?, ?> build, FilePath ws, String glob, TaskListener listener) throws IOException, InterruptedException { public WorkspaceSnapshot snapshot(AbstractBuild<?, ?> build, FilePath ws, String glob, TaskListener listener) throws IOException, InterruptedException {
File wss = new File(build.getRootDir(),"workspace.tgz"); File wss = new File(build.getRootDir(),"workspace.tgz");
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(wss))) { try (OutputStream os = new BufferedOutputStream(Files.newOutputStream(wss.toPath()))) {
ws.archive(ArchiverFactory.TARGZ, os, glob); ws.archive(ArchiverFactory.TARGZ, os, glob);
} }
return new WorkspaceSnapshotImpl(); return new WorkspaceSnapshotImpl();
......
...@@ -23,6 +23,9 @@ ...@@ -23,6 +23,9 @@
*/ */
package hudson; package hudson;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import jenkins.util.SystemProperties; import jenkins.util.SystemProperties;
import hudson.util.DualOutputStream; import hudson.util.DualOutputStream;
import hudson.util.EncodingStream; import hudson.util.EncodingStream;
...@@ -135,11 +138,9 @@ public class Main { ...@@ -135,11 +138,9 @@ public class Main {
// write the output to a temporary file first. // write the output to a temporary file first.
File tmpFile = File.createTempFile("jenkins","log"); File tmpFile = File.createTempFile("jenkins","log");
try { try {
FileOutputStream os = new FileOutputStream(tmpFile);
Writer w = new OutputStreamWriter(os,"UTF-8");
int ret; int ret;
try { try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
Writer w = new OutputStreamWriter(os,"UTF-8")) {
w.write("<?xml version='1.0' encoding='UTF-8'?>"); w.write("<?xml version='1.0' encoding='UTF-8'?>");
w.write("<run><log encoding='hexBinary' content-encoding='"+Charset.defaultCharset().name()+"'>"); w.write("<run><log encoding='hexBinary' content-encoding='"+Charset.defaultCharset().name()+"'>");
w.flush(); w.flush();
...@@ -156,8 +157,6 @@ public class Main { ...@@ -156,8 +157,6 @@ public class Main {
ret = proc.join(); ret = proc.join();
w.write("</log><result>"+ret+"</result><duration>"+(System.currentTimeMillis()-start)+"</duration></run>"); w.write("</log><result>"+ret+"</result><duration>"+(System.currentTimeMillis()-start)+"</duration></run>");
} finally {
IOUtils.closeQuietly(w);
} }
URL location = new URL(jobURL, "postBuildResult"); URL location = new URL(jobURL, "postBuildResult");
...@@ -174,11 +173,8 @@ public class Main { ...@@ -174,11 +173,8 @@ public class Main {
con.setFixedLengthStreamingMode((int)tmpFile.length()); con.setFixedLengthStreamingMode((int)tmpFile.length());
con.connect(); con.connect();
// send the data // send the data
FileInputStream in = new FileInputStream(tmpFile); try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
try {
Util.copyStream(in,con.getOutputStream()); Util.copyStream(in,con.getOutputStream());
} finally {
IOUtils.closeQuietly(in);
} }
if(con.getResponseCode()!=200) { if(con.getResponseCode()!=200) {
......
...@@ -29,6 +29,7 @@ import hudson.PluginManager.PluginInstanceStore; ...@@ -29,6 +29,7 @@ import hudson.PluginManager.PluginInstanceStore;
import hudson.model.AdministrativeMonitor; import hudson.model.AdministrativeMonitor;
import hudson.model.Api; import hudson.model.Api;
import hudson.model.ModelObject; import hudson.model.ModelObject;
import java.nio.file.Files;
import jenkins.YesNoMaybe; import jenkins.YesNoMaybe;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import hudson.model.UpdateCenter; import hudson.model.UpdateCenter;
...@@ -495,7 +496,7 @@ public class PluginWrapper implements Comparable<PluginWrapper>, ModelObject { ...@@ -495,7 +496,7 @@ public class PluginWrapper implements Comparable<PluginWrapper>, ModelObject {
*/ */
public void disable() throws IOException { public void disable() throws IOException {
// creates an empty file // creates an empty file
OutputStream os = new FileOutputStream(disableFile); OutputStream os = Files.newOutputStream(disableFile.toPath());
os.close(); os.close();
} }
......
...@@ -198,7 +198,7 @@ public class Util { ...@@ -198,7 +198,7 @@ public class Util {
StringBuilder str = new StringBuilder((int)logfile.length()); StringBuilder str = new StringBuilder((int)logfile.length());
try (BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile), charset))) { try (BufferedReader r = new BufferedReader(new InputStreamReader(Files.newInputStream(logfile.toPath()), charset))) {
char[] buf = new char[1024]; char[] buf = new char[1024];
int len; int len;
while ((len = r.read(buf, 0, buf.length)) > 0) while ((len = r.read(buf, 0, buf.length)) > 0)
...@@ -800,7 +800,7 @@ public class Util { ...@@ -800,7 +800,7 @@ public class Util {
*/ */
@Nonnull @Nonnull
public static String getDigestOf(@Nonnull File file) throws IOException { public static String getDigestOf(@Nonnull File file) throws IOException {
try (InputStream is = new FileInputStream(file)) { try (InputStream is = Files.newInputStream(file.toPath())) {
return getDigestOf(new BufferedInputStream(is)); return getDigestOf(new BufferedInputStream(is));
} }
} }
...@@ -1134,7 +1134,7 @@ public class Util { ...@@ -1134,7 +1134,7 @@ public class Util {
* Creates an empty file. * Creates an empty file.
*/ */
public static void touch(@Nonnull File file) throws IOException { public static void touch(@Nonnull File file) throws IOException {
new FileOutputStream(file).close(); Files.newOutputStream(file.toPath()).close();
} }
/** /**
......
...@@ -24,6 +24,9 @@ ...@@ -24,6 +24,9 @@
package hudson; package hudson;
import hudson.security.ACLContext; import hudson.security.ACLContext;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import jenkins.util.SystemProperties; import jenkins.util.SystemProperties;
import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider; import com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider;
import com.thoughtworks.xstream.core.JVM; import com.thoughtworks.xstream.core.JVM;
...@@ -273,14 +276,10 @@ public class WebAppMain implements ServletContextListener { ...@@ -273,14 +276,10 @@ public class WebAppMain implements ServletContextListener {
* @see BootFailure * @see BootFailure
*/ */
private void recordBootAttempt(File home) { private void recordBootAttempt(File home) {
FileOutputStream o=null; try (OutputStream o=Files.newOutputStream(BootFailure.getBootFailureFile(home).toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
try {
o = new FileOutputStream(BootFailure.getBootFailureFile(home), true);
o.write((new Date().toString() + System.getProperty("line.separator", "\n")).toString().getBytes()); o.write((new Date().toString() + System.getProperty("line.separator", "\n")).toString().getBytes());
} catch (IOException e) { } catch (IOException e) {
LOGGER.log(WARNING, "Failed to record boot attempts",e); LOGGER.log(WARNING, "Failed to record boot attempts",e);
} finally {
IOUtils.closeQuietly(o);
} }
} }
......
...@@ -33,6 +33,7 @@ import hudson.diagnosis.OldDataMonitor; ...@@ -33,6 +33,7 @@ import hudson.diagnosis.OldDataMonitor;
import hudson.model.Descriptor; import hudson.model.Descriptor;
import hudson.util.AtomicFileWriter; import hudson.util.AtomicFileWriter;
import hudson.util.XStream2; import hudson.util.XStream2;
import java.nio.file.Files;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.Locator; import org.xml.sax.Locator;
...@@ -138,7 +139,7 @@ public final class XmlFile { ...@@ -138,7 +139,7 @@ public final class XmlFile {
if (LOGGER.isLoggable(Level.FINE)) { if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Reading "+file); LOGGER.fine("Reading "+file);
} }
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
return xs.fromXML(in); return xs.fromXML(in);
} catch (XStreamException | Error e) { } catch (XStreamException | Error e) {
throw new IOException("Unable to read "+file,e); throw new IOException("Unable to read "+file,e);
...@@ -154,7 +155,7 @@ public final class XmlFile { ...@@ -154,7 +155,7 @@ public final class XmlFile {
*/ */
public Object unmarshal( Object o ) throws IOException { public Object unmarshal( Object o ) throws IOException {
try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
// TODO: expose XStream the driver from XStream // TODO: expose XStream the driver from XStream
return xs.unmarshal(DEFAULT_DRIVER.createReader(in), o); return xs.unmarshal(DEFAULT_DRIVER.createReader(in), o);
} catch (XStreamException | Error e) { } catch (XStreamException | Error e) {
...@@ -201,7 +202,7 @@ public final class XmlFile { ...@@ -201,7 +202,7 @@ public final class XmlFile {
* @return Reader for the file. should be close externally once read. * @return Reader for the file. should be close externally once read.
*/ */
public Reader readRaw() throws IOException { public Reader readRaw() throws IOException {
FileInputStream fileInputStream = new FileInputStream(file); InputStream fileInputStream = Files.newInputStream(file.toPath());
try { try {
return new InputStreamReader(fileInputStream, sniffEncoding()); return new InputStreamReader(fileInputStream, sniffEncoding());
} catch(IOException ex) { } catch(IOException ex) {
...@@ -247,7 +248,7 @@ public final class XmlFile { ...@@ -247,7 +248,7 @@ public final class XmlFile {
} }
} }
try (InputStream in = new FileInputStream(file)) { try (InputStream in = Files.newInputStream(file.toPath())) {
InputSource input = new InputSource(file.toURI().toASCIIString()); InputSource input = new InputSource(file.toURI().toASCIIString());
input.setByteStream(in); input.setByteStream(in);
JAXP.newSAXParser().parse(input,new DefaultHandler() { JAXP.newSAXParser().parse(input,new DefaultHandler() {
......
...@@ -31,6 +31,8 @@ import hudson.model.TaskListener; ...@@ -31,6 +31,8 @@ import hudson.model.TaskListener;
import hudson.util.jna.Kernel32Utils; import hudson.util.jna.Kernel32Utils;
import hudson.util.jna.SHELLEXECUTEINFO; import hudson.util.jna.SHELLEXECUTEINFO;
import hudson.util.jna.Shell32; import hudson.util.jna.Shell32;
import java.io.InputStream;
import java.nio.file.Files;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import hudson.AbortException; import hudson.AbortException;
import hudson.Extension; import hudson.Extension;
...@@ -306,7 +308,7 @@ public class WindowsInstallerLink extends ManagementLink { ...@@ -306,7 +308,7 @@ public class WindowsInstallerLink extends ManagementLink {
try { try {
return Kernel32Utils.waitForExitProcess(sei.hProcess); return Kernel32Utils.waitForExitProcess(sei.hProcess);
} finally { } finally {
try (FileInputStream fin = new FileInputStream(new File(pwd,"redirect.log"))) { try (InputStream fin = Files.newInputStream(new File(pwd,"redirect.log").toPath())) {
IOUtils.copy(fin, out.getLogger()); IOUtils.copy(fin, out.getLogger());
} }
} }
......
...@@ -36,6 +36,7 @@ import java.io.IOException; ...@@ -36,6 +36,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import javax.servlet.ServletException; import javax.servlet.ServletException;
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItem;
...@@ -205,7 +206,7 @@ public class FileParameterValue extends ParameterValue { ...@@ -205,7 +206,7 @@ public class FileParameterValue extends ParameterValue {
AbstractBuild build = (AbstractBuild)request.findAncestor(AbstractBuild.class).getObject(); AbstractBuild build = (AbstractBuild)request.findAncestor(AbstractBuild.class).getObject();
File fileParameter = getLocationUnderBuild(build); File fileParameter = getLocationUnderBuild(build);
if (fileParameter.isFile()) { if (fileParameter.isFile()) {
InputStream data = new FileInputStream(fileParameter); InputStream data = Files.newInputStream(fileParameter.toPath());
try { try {
long lastModified = fileParameter.lastModified(); long lastModified = fileParameter.lastModified();
long contentLength = fileParameter.length(); long contentLength = fileParameter.length();
...@@ -245,7 +246,7 @@ public class FileParameterValue extends ParameterValue { ...@@ -245,7 +246,7 @@ public class FileParameterValue extends ParameterValue {
} }
public InputStream getInputStream() throws IOException { public InputStream getInputStream() throws IOException {
return new FileInputStream(file); return Files.newInputStream(file.toPath());
} }
public String getContentType() { public String getContentType() {
...@@ -266,7 +267,7 @@ public class FileParameterValue extends ParameterValue { ...@@ -266,7 +267,7 @@ public class FileParameterValue extends ParameterValue {
public byte[] get() { public byte[] get() {
try { try {
try (FileInputStream inputStream = new FileInputStream(file)) { try (InputStream inputStream = Files.newInputStream(file.toPath())) {
return IOUtils.toByteArray(inputStream); return IOUtils.toByteArray(inputStream);
} }
} catch (IOException e) { } catch (IOException e) {
...@@ -306,7 +307,7 @@ public class FileParameterValue extends ParameterValue { ...@@ -306,7 +307,7 @@ public class FileParameterValue extends ParameterValue {
@Deprecated @Deprecated
public OutputStream getOutputStream() throws IOException { public OutputStream getOutputStream() throws IOException {
return new FileOutputStream(file); return Files.newOutputStream(file.toPath());
} }
@Override @Override
......
...@@ -63,6 +63,7 @@ import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy; ...@@ -63,6 +63,7 @@ import hudson.model.queue.CauseOfBlockage.BecauseNodeIsBusy;
import hudson.model.queue.WorkUnitContext; import hudson.model.queue.WorkUnitContext;
import hudson.security.ACL; import hudson.security.ACL;
import hudson.security.AccessControlled; import hudson.security.AccessControlled;
import java.nio.file.Files;
import jenkins.security.QueueItemAuthenticatorProvider; import jenkins.security.QueueItemAuthenticatorProvider;
import jenkins.util.Timer; import jenkins.util.Timer;
import hudson.triggers.SafeTimerTask; import hudson.triggers.SafeTimerTask;
...@@ -376,7 +377,7 @@ public class Queue extends ResourceController implements Saveable { ...@@ -376,7 +377,7 @@ public class Queue extends ResourceController implements Saveable {
// first try the old format // first try the old format
File queueFile = getQueueFile(); File queueFile = getQueueFile();
if (queueFile.exists()) { if (queueFile.exists()) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(queueFile)))) { try (BufferedReader in = new BufferedReader(new InputStreamReader(Files.newInputStream(queueFile.toPath())))) {
String line; String line;
while ((line = in.readLine()) != null) { while ((line = in.readLine()) != null) {
AbstractProject j = Jenkins.getInstance().getItemByFullName(line, AbstractProject.class); AbstractProject j = Jenkins.getInstance().getItemByFullName(line, AbstractProject.class);
......
...@@ -41,6 +41,8 @@ import hudson.console.ConsoleLogFilter; ...@@ -41,6 +41,8 @@ import hudson.console.ConsoleLogFilter;
import hudson.console.ConsoleNote; import hudson.console.ConsoleNote;
import hudson.console.ModelHyperlinkNote; import hudson.console.ModelHyperlinkNote;
import hudson.console.PlainTextConsoleOutputStream; import hudson.console.PlainTextConsoleOutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import jenkins.util.SystemProperties; import jenkins.util.SystemProperties;
import hudson.Util; import hudson.Util;
import hudson.XmlFile; import hudson.XmlFile;
...@@ -1367,7 +1369,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run ...@@ -1367,7 +1369,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
if (logFile.exists() ) { if (logFile.exists() ) {
// Checking if a ".gz" file was return // Checking if a ".gz" file was return
FileInputStream fis = new FileInputStream(logFile); InputStream fis = Files.newInputStream(logFile.toPath());
if (logFile.getName().endsWith(".gz")) { if (logFile.getName().endsWith(".gz")) {
return new GZIPInputStream(fis); return new GZIPInputStream(fis);
} else { } else {
...@@ -1807,7 +1809,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run ...@@ -1807,7 +1809,7 @@ public abstract class Run <JobT extends Job<JobT,RunT>,RunT extends Run<JobT,Run
// don't do buffering so that what's written to the listener // don't do buffering so that what's written to the listener
// gets reflected to the file immediately, which can then be // gets reflected to the file immediately, which can then be
// served to the browser immediately // served to the browser immediately
OutputStream logger = new FileOutputStream(getLogFile(), true); OutputStream logger = Files.newOutputStream(getLogFile().toPath(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
RunT build = job.getBuild(); RunT build = job.getBuild();
// Global log filters // Global log filters
......
...@@ -31,6 +31,7 @@ import hudson.PluginManager; ...@@ -31,6 +31,7 @@ import hudson.PluginManager;
import hudson.PluginWrapper; import hudson.PluginWrapper;
import hudson.ProxyConfiguration; import hudson.ProxyConfiguration;
import hudson.security.ACLContext; import hudson.security.ACLContext;
import java.nio.file.Files;
import jenkins.util.SystemProperties; import jenkins.util.SystemProperties;
import hudson.Util; import hudson.Util;
import hudson.XmlFile; import hudson.XmlFile;
...@@ -1127,7 +1128,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas ...@@ -1127,7 +1128,7 @@ public class UpdateCenter extends AbstractModelObject implements Saveable, OnMas
File dst = job.getDestination(); File dst = job.getDestination();
File tmp = new File(dst.getPath()+".tmp"); File tmp = new File(dst.getPath()+".tmp");
out = new FileOutputStream(tmp); out = Files.newOutputStream(tmp.toPath());
if (sha1 != null) { if (sha1 != null) {
out = new DigestOutputStream(out, sha1); out = new DigestOutputStream(out, sha1);
} }
......
...@@ -39,6 +39,8 @@ import hudson.util.ArgumentListBuilder; ...@@ -39,6 +39,8 @@ import hudson.util.ArgumentListBuilder;
import hudson.util.FormValidation; import hudson.util.FormValidation;
import hudson.util.HttpResponses; import hudson.util.HttpResponses;
import hudson.util.Secret; import hudson.util.Secret;
import java.io.OutputStream;
import java.nio.file.Files;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import jenkins.security.MasterToSlaveCallable; import jenkins.security.MasterToSlaveCallable;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
...@@ -519,7 +521,7 @@ public class JDKInstaller extends ToolInstaller { ...@@ -519,7 +521,7 @@ public class JDKInstaller extends ToolInstaller {
File tmp = new File(cache.getPath()+".tmp"); File tmp = new File(cache.getPath()+".tmp");
try { try {
tmp.getParentFile().mkdirs(); tmp.getParentFile().mkdirs();
try (FileOutputStream out = new FileOutputStream(tmp)) { try (OutputStream out = Files.newOutputStream(tmp.toPath())) {
IOUtils.copy(m.getResponseBodyAsStream(), out); IOUtils.copy(m.getResponseBodyAsStream(), out);
} }
......
...@@ -32,6 +32,7 @@ import java.io.IOException; ...@@ -32,6 +32,7 @@ import java.io.IOException;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files;
/** /**
* Buffered {@link FileWriter} that supports atomic operations. * Buffered {@link FileWriter} that supports atomic operations.
...@@ -70,7 +71,7 @@ public class AtomicFileWriter extends Writer { ...@@ -70,7 +71,7 @@ public class AtomicFileWriter extends Writer {
destFile = f; destFile = f;
if (encoding==null) if (encoding==null)
encoding = Charset.defaultCharset().name(); encoding = Charset.defaultCharset().name();
core = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile),encoding)); core = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(tmpFile.toPath()),encoding));
} }
@Override @Override
......
...@@ -23,25 +23,23 @@ ...@@ -23,25 +23,23 @@
*/ */
package hudson.util; package hudson.util;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
import hudson.Util; import hudson.Util;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.Reader; import java.io.Reader;
import java.nio.file.Files;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import com.jcraft.jzlib.GZIPInputStream;
import com.jcraft.jzlib.GZIPOutputStream;
/** /**
* Represents write-once read-many file that can be optionally compressed * Represents write-once read-many file that can be optionally compressed
...@@ -78,10 +76,10 @@ public class CompressedFile { ...@@ -78,10 +76,10 @@ public class CompressedFile {
/** /**
* Gets the OutputStream to write to the file. * Gets the OutputStream to write to the file.
*/ */
public OutputStream write() throws FileNotFoundException { public OutputStream write() throws IOException {
if(gz.exists()) if(gz.exists())
gz.delete(); gz.delete();
return new FileOutputStream(file); return Files.newOutputStream(file.toPath());
} }
/** /**
...@@ -89,11 +87,11 @@ public class CompressedFile { ...@@ -89,11 +87,11 @@ public class CompressedFile {
*/ */
public InputStream read() throws IOException { public InputStream read() throws IOException {
if(file.exists()) if(file.exists())
return new FileInputStream(file); return Files.newInputStream(file.toPath());
// check if the compressed file exists // check if the compressed file exists
if(gz.exists()) if(gz.exists())
return new GZIPInputStream(new FileInputStream(gz)); return new GZIPInputStream(Files.newInputStream(gz.toPath()));
// no such file // no such file
throw new FileNotFoundException(file.getName()); throw new FileNotFoundException(file.getName());
...@@ -138,7 +136,8 @@ public class CompressedFile { ...@@ -138,7 +136,8 @@ public class CompressedFile {
compressionThread.submit(new Runnable() { compressionThread.submit(new Runnable() {
public void run() { public void run() {
try { try {
try (InputStream in = read(); OutputStream out = new GZIPOutputStream(new FileOutputStream(gz))) { try (InputStream in = read();
OutputStream out = new GZIPOutputStream(Files.newOutputStream(gz.toPath()))) {
Util.copyStream(in, out); Util.copyStream(in, out);
} }
// if the compressed file is created successfully, remove the original // if the compressed file is created successfully, remove the original
......
...@@ -3,6 +3,7 @@ package hudson.util; ...@@ -3,6 +3,7 @@ package hudson.util;
import hudson.Functions; import hudson.Functions;
import hudson.os.PosixAPI; import hudson.os.PosixAPI;
import hudson.os.PosixException; import hudson.os.PosixException;
import java.nio.file.Files;
import org.apache.commons.io.LineIterator; import org.apache.commons.io.LineIterator;
import java.io.*; import java.io.*;
...@@ -26,20 +27,14 @@ public class IOUtils { ...@@ -26,20 +27,14 @@ public class IOUtils {
} }
public static void copy(File src, OutputStream out) throws IOException { public static void copy(File src, OutputStream out) throws IOException {
FileInputStream in = new FileInputStream(src); try (InputStream in = Files.newInputStream(src.toPath())) {
try {
org.apache.commons.io.IOUtils.copy(in, out); org.apache.commons.io.IOUtils.copy(in, out);
} finally {
org.apache.commons.io.IOUtils.closeQuietly(in);
} }
} }
public static void copy(InputStream in, File out) throws IOException { public static void copy(InputStream in, File out) throws IOException {
FileOutputStream fos = new FileOutputStream(out); try (OutputStream fos = Files.newOutputStream(out.toPath())) {
try {
org.apache.commons.io.IOUtils.copy(in, fos); org.apache.commons.io.IOUtils.copy(in, fos);
} finally {
org.apache.commons.io.IOUtils.closeQuietly(fos);
} }
} }
......
...@@ -4,6 +4,8 @@ import com.trilead.ssh2.crypto.Base64; ...@@ -4,6 +4,8 @@ import com.trilead.ssh2.crypto.Base64;
import hudson.Functions; import hudson.Functions;
import hudson.model.TaskListener; import hudson.model.TaskListener;
import java.io.InputStream;
import java.nio.file.Files;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import java.io.BufferedReader; import java.io.BufferedReader;
...@@ -84,7 +86,7 @@ public class SecretRewriter { ...@@ -84,7 +86,7 @@ public class SecretRewriter {
boolean modified = false; // did we actually change anything? boolean modified = false; // did we actually change anything?
try (PrintWriter out = new PrintWriter(new BufferedWriter(w))) { try (PrintWriter out = new PrintWriter(new BufferedWriter(w))) {
try (FileInputStream fin = new FileInputStream(f)) { try (InputStream fin = Files.newInputStream(f.toPath())) {
BufferedReader r = new BufferedReader(new InputStreamReader(fin, "UTF-8")); BufferedReader r = new BufferedReader(new InputStreamReader(fin, "UTF-8"));
String line; String line;
StringBuilder buf = new StringBuilder(); StringBuilder buf = new StringBuilder();
......
...@@ -30,7 +30,6 @@ import hudson.model.TaskListener; ...@@ -30,7 +30,6 @@ import hudson.model.TaskListener;
import hudson.remoting.RemoteOutputStream; import hudson.remoting.RemoteOutputStream;
import java.io.Closeable; import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
...@@ -42,6 +41,9 @@ import java.io.Serializable; ...@@ -42,6 +41,9 @@ import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.io.Writer; import java.io.Writer;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.StandardOpenOption;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import org.kohsuke.stapler.framework.io.WriterOutputStream; import org.kohsuke.stapler.framework.io.WriterOutputStream;
...@@ -94,7 +96,7 @@ public class StreamTaskListener extends AbstractTaskListener implements Serializ ...@@ -94,7 +96,7 @@ public class StreamTaskListener extends AbstractTaskListener implements Serializ
// don't do buffering so that what's written to the listener // don't do buffering so that what's written to the listener
// gets reflected to the file immediately, which can then be // gets reflected to the file immediately, which can then be
// served to the browser immediately // served to the browser immediately
this(new FileOutputStream(out),charset); this(Files.newOutputStream(out.toPath()),charset);
} }
/** /**
...@@ -110,7 +112,12 @@ public class StreamTaskListener extends AbstractTaskListener implements Serializ ...@@ -110,7 +112,12 @@ public class StreamTaskListener extends AbstractTaskListener implements Serializ
// don't do buffering so that what's written to the listener // don't do buffering so that what's written to the listener
// gets reflected to the file immediately, which can then be // gets reflected to the file immediately, which can then be
// served to the browser immediately // served to the browser immediately
this(new FileOutputStream(out, append),charset); this(Files.newOutputStream(
out.toPath(),
StandardOpenOption.CREATE, append ? StandardOpenOption.APPEND: StandardOpenOption.TRUNCATE_EXISTING
),
charset
);
} }
public StreamTaskListener(Writer w) throws IOException { public StreamTaskListener(Writer w) throws IOException {
......
...@@ -25,6 +25,7 @@ package hudson.util; ...@@ -25,6 +25,7 @@ package hudson.util;
import com.google.common.collect.*; import com.google.common.collect.*;
import java.nio.file.Files;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
...@@ -67,7 +68,7 @@ public class TextFile { ...@@ -67,7 +68,7 @@ public class TextFile {
public String read() throws IOException { public String read() throws IOException {
StringWriter out = new StringWriter(); StringWriter out = new StringWriter();
PrintWriter w = new PrintWriter(out); PrintWriter w = new PrintWriter(out);
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) { try (BufferedReader in = new BufferedReader(new InputStreamReader(Files.newInputStream(file.toPath()), "UTF-8"))) {
String line; String line;
while ((line = in.readLine()) != null) while ((line = in.readLine()) != null)
w.println(line); w.println(line);
...@@ -83,7 +84,8 @@ public class TextFile { ...@@ -83,7 +84,8 @@ public class TextFile {
@Override @Override
public Iterator<String> iterator() { public Iterator<String> iterator() {
try { try {
final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); final BufferedReader in = new BufferedReader(new InputStreamReader(
Files.newInputStream(file.toPath()),"UTF-8"));
return new AbstractIterator<String>() { return new AbstractIterator<String>() {
@Override @Override
......
...@@ -28,6 +28,8 @@ import java.io.FileNotFoundException; ...@@ -28,6 +28,8 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
/** /**
* {@link OutputStream} that writes to a file. * {@link OutputStream} that writes to a file.
...@@ -52,7 +54,8 @@ import java.io.OutputStream; ...@@ -52,7 +54,8 @@ import java.io.OutputStream;
private synchronized OutputStream current() throws IOException { private synchronized OutputStream current() throws IOException {
if (current==null) if (current==null)
try { try {
current = new FileOutputStream(out,appendOnNextOpen); current = Files.newOutputStream(out.toPath(), StandardOpenOption.CREATE,
appendOnNextOpen ? StandardOpenOption.APPEND : StandardOpenOption.TRUNCATE_EXISTING);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new IOException("Failed to open "+out,e); throw new IOException("Failed to open "+out,e);
} }
......
...@@ -28,6 +28,8 @@ import java.io.FileNotFoundException; ...@@ -28,6 +28,8 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
/** /**
...@@ -51,7 +53,7 @@ public class RewindableFileOutputStream extends OutputStream { ...@@ -51,7 +53,7 @@ public class RewindableFileOutputStream extends OutputStream {
if (!closed) { if (!closed) {
FileUtils.forceMkdir(out.getParentFile()); FileUtils.forceMkdir(out.getParentFile());
try { try {
current = new FileOutputStream(out,false); current = Files.newOutputStream(out.toPath(), StandardOpenOption.TRUNCATE_EXISTING);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new IOException("Failed to open "+out,e); throw new IOException("Failed to open "+out,e);
} }
......
...@@ -32,8 +32,10 @@ import hudson.util.IOUtils; ...@@ -32,8 +32,10 @@ import hudson.util.IOUtils;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.nio.file.Files;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.archivers.tar.TarConstants; import org.apache.commons.compress.archivers.tar.TarConstants;
...@@ -100,7 +102,7 @@ final class TarArchiver extends Archiver { ...@@ -100,7 +102,7 @@ final class TarArchiver extends Archiver {
if (!file.isDirectory()) { if (!file.isDirectory()) {
// ensure we don't write more bytes than the declared when we created the entry // ensure we don't write more bytes than the declared when we created the entry
try (FileInputStream fin = new FileInputStream(file); try (InputStream fin = Files.newInputStream(file.toPath());
BoundedInputStream in = new BoundedInputStream(fin, size)) { BoundedInputStream in = new BoundedInputStream(fin, size)) {
int len; int len;
while ((len = in.read(buf)) >= 0) { while ((len = in.read(buf)) >= 0) {
......
...@@ -26,6 +26,8 @@ package hudson.util.io; ...@@ -26,6 +26,8 @@ package hudson.util.io;
import hudson.util.FileVisitor; import hudson.util.FileVisitor;
import hudson.util.IOUtils; import hudson.util.IOUtils;
import java.io.InputStream;
import java.nio.file.Files;
import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream; import org.apache.tools.zip.ZipOutputStream;
...@@ -69,13 +71,10 @@ final class ZipArchiver extends Archiver { ...@@ -69,13 +71,10 @@ final class ZipArchiver extends Archiver {
if (mode!=-1) fileZipEntry.setUnixMode(mode); if (mode!=-1) fileZipEntry.setUnixMode(mode);
fileZipEntry.setTime(f.lastModified()); fileZipEntry.setTime(f.lastModified());
zip.putNextEntry(fileZipEntry); zip.putNextEntry(fileZipEntry);
FileInputStream in = new FileInputStream(f); try (InputStream in = Files.newInputStream(f.toPath())) {
try {
int len; int len;
while((len=in.read(buf))>=0) while((len=in.read(buf))>=0)
zip.write(buf,0,len); zip.write(buf,0,len);
} finally {
in.close();
} }
zip.closeEntry(); zip.closeEntry();
} }
......
...@@ -6,6 +6,9 @@ import hudson.Functions; ...@@ -6,6 +6,9 @@ import hudson.Functions;
import hudson.Util; import hudson.Util;
import hudson.model.AdministrativeMonitor; import hudson.model.AdministrativeMonitor;
import hudson.util.jna.Kernel32Utils; import hudson.util.jna.Kernel32Utils;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.StandardOpenOption;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project; import org.apache.tools.ant.Project;
...@@ -49,7 +52,7 @@ public class HsErrPidList extends AdministrativeMonitor { ...@@ -49,7 +52,7 @@ public class HsErrPidList extends AdministrativeMonitor {
return; return;
} }
try { try {
try (FileChannel ch = new FileInputStream(getSecretKeyFile()).getChannel()) { try (FileChannel ch = FileChannel.open(getSecretKeyFile().toPath(), StandardOpenOption.READ)) {
map = ch.map(MapMode.READ_ONLY,0,1); map = ch.map(MapMode.READ_ONLY,0,1);
} }
......
...@@ -4,6 +4,9 @@ import hudson.FilePath; ...@@ -4,6 +4,9 @@ import hudson.FilePath;
import hudson.Util; import hudson.Util;
import hudson.util.Secret; import hudson.util.Secret;
import hudson.util.TextFile; import hudson.util.TextFile;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import javax.crypto.Cipher; import javax.crypto.Cipher;
...@@ -72,11 +75,11 @@ public class DefaultConfidentialStore extends ConfidentialStore { ...@@ -72,11 +75,11 @@ public class DefaultConfidentialStore extends ConfidentialStore {
@Override @Override
protected void store(ConfidentialKey key, byte[] payload) throws IOException { protected void store(ConfidentialKey key, byte[] payload) throws IOException {
CipherOutputStream cos=null; CipherOutputStream cos=null;
FileOutputStream fos=null; OutputStream fos=null;
try { try {
Cipher sym = Secret.getCipher("AES"); Cipher sym = Secret.getCipher("AES");
sym.init(Cipher.ENCRYPT_MODE, masterKey); sym.init(Cipher.ENCRYPT_MODE, masterKey);
cos = new CipherOutputStream(fos=new FileOutputStream(getFileFor(key)), sym); cos = new CipherOutputStream(fos= Files.newOutputStream(getFileFor(key).toPath()), sym);
cos.write(payload); cos.write(payload);
cos.write(MAGIC); cos.write(MAGIC);
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException e) {
...@@ -96,14 +99,14 @@ public class DefaultConfidentialStore extends ConfidentialStore { ...@@ -96,14 +99,14 @@ public class DefaultConfidentialStore extends ConfidentialStore {
@Override @Override
protected byte[] load(ConfidentialKey key) throws IOException { protected byte[] load(ConfidentialKey key) throws IOException {
CipherInputStream cis=null; CipherInputStream cis=null;
FileInputStream fis=null; InputStream fis=null;
try { try {
File f = getFileFor(key); File f = getFileFor(key);
if (!f.exists()) return null; if (!f.exists()) return null;
Cipher sym = Secret.getCipher("AES"); Cipher sym = Secret.getCipher("AES");
sym.init(Cipher.DECRYPT_MODE, masterKey); sym.init(Cipher.DECRYPT_MODE, masterKey);
cis = new CipherInputStream(fis=new FileInputStream(f), sym); cis = new CipherInputStream(fis=Files.newInputStream(f.toPath()), sym);
byte[] bytes = IOUtils.toByteArray(cis); byte[] bytes = IOUtils.toByteArray(cis);
return verifyMagic(bytes); return verifyMagic(bytes);
} catch (GeneralSecurityException e) { } catch (GeneralSecurityException e) {
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
*/ */
package jenkins.util; package jenkins.util;
import java.nio.file.Files;
import org.apache.tools.ant.BuildEvent; import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project; import org.apache.tools.ant.Project;
...@@ -790,7 +791,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener { ...@@ -790,7 +791,7 @@ public class AntClassLoader extends ClassLoader implements SubBuildListener {
if (jarFile == null && file.isDirectory()) { if (jarFile == null && file.isDirectory()) {
File resource = new File(file, resourceName); File resource = new File(file, resourceName);
if (resource.exists()) { if (resource.exists()) {
return new FileInputStream(resource); return Files.newInputStream(resource.toPath());
} }
} else { } else {
if (jarFile == null) { if (jarFile == null) {
......
...@@ -2,6 +2,7 @@ package jenkins.util; ...@@ -2,6 +2,7 @@ package jenkins.util;
import com.trilead.ssh2.crypto.Base64; import com.trilead.ssh2.crypto.Base64;
import hudson.util.FormValidation; import hudson.util.FormValidation;
import java.nio.file.Files;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import org.apache.commons.io.output.NullOutputStream; import org.apache.commons.io.output.NullOutputStream;
...@@ -173,9 +174,8 @@ public class JSONSignatureValidator { ...@@ -173,9 +174,8 @@ public class JSONSignatureValidator {
if (cert.isDirectory() || cert.getName().endsWith(".txt")) { if (cert.isDirectory() || cert.getName().endsWith(".txt")) {
continue; // skip directories also any text files that are meant to be documentation continue; // skip directories also any text files that are meant to be documentation
} }
FileInputStream in = new FileInputStream(cert);
Certificate certificate; Certificate certificate;
try { try (InputStream in = Files.newInputStream(cert.toPath())) {
certificate = cf.generateCertificate(in); certificate = cf.generateCertificate(in);
} catch (CertificateException e) { } catch (CertificateException e) {
LOGGER.log(Level.WARNING, String.format("Files in %s are expected to be either " LOGGER.log(Level.WARNING, String.format("Files in %s are expected to be either "
...@@ -184,8 +184,6 @@ public class JSONSignatureValidator { ...@@ -184,8 +184,6 @@ public class JSONSignatureValidator {
cert.getParentFile().getAbsolutePath(), cert.getParentFile().getAbsolutePath(),
cert.getAbsolutePath()), e); cert.getAbsolutePath()), e);
continue; continue;
} finally {
in.close();
} }
try { try {
TrustAnchor certificateAuthority = new TrustAnchor((X509Certificate) certificate, null); TrustAnchor certificateAuthority = new TrustAnchor((X509Certificate) certificate, null);
......
...@@ -38,6 +38,7 @@ import java.io.IOException; ...@@ -38,6 +38,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.Serializable; import java.io.Serializable;
import java.net.URI; import java.net.URI;
import java.nio.file.Files;
import java.nio.file.InvalidPathException; import java.nio.file.InvalidPathException;
import java.nio.file.LinkOption; import java.nio.file.LinkOption;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -295,7 +296,7 @@ public abstract class VirtualFile implements Comparable<VirtualFile>, Serializab ...@@ -295,7 +296,7 @@ public abstract class VirtualFile implements Comparable<VirtualFile>, Serializab
if (isIllegalSymlink()) { if (isIllegalSymlink()) {
throw new FileNotFoundException(f.getPath()); throw new FileNotFoundException(f.getPath());
} }
return new FileInputStream(f); return Files.newInputStream(f.toPath());
} }
private boolean isIllegalSymlink() { // TODO JENKINS-26838 private boolean isIllegalSymlink() { // TODO JENKINS-26838
try { try {
......
package jenkins.util.io; package jenkins.util.io;
import java.nio.file.Files;
import jenkins.model.Jenkins; import jenkins.model.Jenkins;
import java.io.File; import java.io.File;
...@@ -56,7 +57,7 @@ public class FileBoolean { ...@@ -56,7 +57,7 @@ public class FileBoolean {
public void on() { public void on() {
try { try {
file.getParentFile().mkdirs(); file.getParentFile().mkdirs();
new FileOutputStream(file).close(); Files.newOutputStream(file.toPath()).close();
get(); // update state get(); // update state
} catch (IOException e) { } catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to touch "+file); LOGGER.log(Level.WARNING, "Failed to touch "+file);
......
package jenkins.util.xml; package jenkins.util.xml;
import java.io.InputStream;
import java.nio.file.Files;
import jenkins.util.SystemProperties; import jenkins.util.SystemProperties;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.Restricted;
...@@ -137,16 +139,9 @@ public final class XMLUtils { ...@@ -137,16 +139,9 @@ public final class XMLUtils {
throw new IllegalArgumentException(String.format("File %s does not exist or is not a 'normal' file.", file.getAbsolutePath())); throw new IllegalArgumentException(String.format("File %s does not exist or is not a 'normal' file.", file.getAbsolutePath()));
} }
FileInputStream fileInputStream = new FileInputStream(file); try (InputStream fileInputStream = Files.newInputStream(file.toPath());
try { InputStreamReader fileReader = new InputStreamReader(fileInputStream, encoding)) {
InputStreamReader fileReader = new InputStreamReader(fileInputStream, encoding); return parse(fileReader);
try {
return parse(fileReader);
} finally {
IOUtils.closeQuietly(fileReader);
}
} finally {
IOUtils.closeQuietly(fileInputStream);
} }
} }
......
...@@ -43,6 +43,7 @@ import java.net.URL; ...@@ -43,6 +43,7 @@ import java.net.URL;
import java.net.URLConnection; import java.net.URLConnection;
import java.net.URLStreamHandler; import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory; import java.net.URLStreamHandlerFactory;
import java.nio.file.Files;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
...@@ -134,12 +135,12 @@ public class FilePathTest { ...@@ -134,12 +135,12 @@ public class FilePathTest {
} }
private void givenSomeContentInFile(File file, int size) throws IOException { private void givenSomeContentInFile(File file, int size) throws IOException {
FileOutputStream os = new FileOutputStream(file); try (OutputStream os = Files.newOutputStream(file.toPath())) {
byte[] buf = new byte[size]; byte[] buf = new byte[size];
for (int i=0; i<buf.length; i++) for (int i = 0; i < buf.length; i++)
buf[i] = (byte)(i%256); buf[i] = (byte) (i % 256);
os.write(buf); os.write(buf);
os.close(); }
} }
private List<Future<Integer>> whenFileIsCopied100TimesConcurrently(final File file) throws InterruptedException { private List<Future<Integer>> whenFileIsCopied100TimesConcurrently(final File file) throws InterruptedException {
...@@ -369,7 +370,7 @@ public class FilePathTest { ...@@ -369,7 +370,7 @@ public class FilePathTest {
// Compress archive // Compress archive
final FilePath tmpDirPath = new FilePath(tmpDir); final FilePath tmpDirPath = new FilePath(tmpDir);
int tar = tmpDirPath.tar(new FileOutputStream(tarFile), tempFile.getName()); int tar = tmpDirPath.tar(Files.newOutputStream(tarFile.toPath()), tempFile.getName());
assertEquals("One file should have been compressed", 1, tar); assertEquals("One file should have been compressed", 1, tar);
// Decompress // Decompress
...@@ -725,7 +726,7 @@ public class FilePathTest { ...@@ -725,7 +726,7 @@ public class FilePathTest {
// Compress archive // Compress archive
final FilePath tmpDirPath = new FilePath(srcFolder); final FilePath tmpDirPath = new FilePath(srcFolder);
int tarred = tmpDirPath.tar(new FileOutputStream(archive), "**"); int tarred = tmpDirPath.tar(Files.newOutputStream(archive.toPath()), "**");
assertEquals("One file should have been compressed", 3, tarred); assertEquals("One file should have been compressed", 3, tarred);
// Decompress // Decompress
......
...@@ -26,6 +26,7 @@ package hudson; ...@@ -26,6 +26,7 @@ package hudson;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.nio.file.Files;
import org.apache.tools.ant.filters.StringInputStream; import org.apache.tools.ant.filters.StringInputStream;
import org.junit.Test; import org.junit.Test;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
...@@ -151,7 +152,7 @@ public class PluginManagerTest { ...@@ -151,7 +152,7 @@ public class PluginManagerTest {
FileUtils.write(new File(newFolder, manifestPath), SAMPLE_MANIFEST_FILE); FileUtils.write(new File(newFolder, manifestPath), SAMPLE_MANIFEST_FILE);
final File f = new File(tmp.getRoot(), "my.hpi"); final File f = new File(tmp.getRoot(), "my.hpi");
try(ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) { try(ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(f.toPath()))) {
ZipEntry e = new ZipEntry(manifestPath); ZipEntry e = new ZipEntry(manifestPath);
out.putNextEntry(e); out.putNextEntry(e);
byte[] data = SAMPLE_MANIFEST_FILE.getBytes(); byte[] data = SAMPLE_MANIFEST_FILE.getBytes();
......
...@@ -24,6 +24,7 @@ ...@@ -24,6 +24,7 @@
*/ */
package hudson; package hudson;
import java.nio.file.Files;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.HashMap; import java.util.HashMap;
...@@ -490,7 +491,7 @@ public class UtilTest { ...@@ -490,7 +491,7 @@ public class UtilTest {
// On unix, can't use "chattr +u" because ext fs ignores it. // On unix, can't use "chattr +u" because ext fs ignores it.
// On Windows, we can't delete files that are open for reading, so we use that. // On Windows, we can't delete files that are open for reading, so we use that.
assert Functions.isWindows(); assert Functions.isWindows();
final InputStream s = new FileInputStream(f); final InputStream s = Files.newInputStream(f.toPath());
unlockFileCallables.put(f, new Callable<Void>() { unlockFileCallables.put(f, new Callable<Void>() {
public Void call() throws IOException { s.close(); return null; }; public Void call() throws IOException { s.close(); return null; };
}); });
......
...@@ -26,6 +26,9 @@ package hudson.model; ...@@ -26,6 +26,9 @@ package hudson.model;
import hudson.model.MultiStageTimeSeries.TimeScale; import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.model.queue.SubTask; import hudson.model.queue.SubTask;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.jfree.chart.JFreeChart; import org.jfree.chart.JFreeChart;
import org.junit.Test; import org.junit.Test;
...@@ -87,11 +90,9 @@ public class LoadStatisticsTest { ...@@ -87,11 +90,9 @@ public class LoadStatisticsTest {
BufferedImage image = chart.createBufferedImage(400, 200); BufferedImage image = chart.createBufferedImage(400, 200);
File tempFile = File.createTempFile("chart-", "png"); File tempFile = File.createTempFile("chart-", "png");
FileOutputStream os = new FileOutputStream(tempFile); try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) {
try {
ImageIO.write(image, "PNG", os); ImageIO.write(image, "PNG", os);
} finally { } finally {
IOUtils.closeQuietly(os);
tempFile.delete(); tempFile.delete();
} }
} }
......
package hudson.os; package hudson.os;
import hudson.util.StreamTaskListener; import hudson.util.StreamTaskListener;
import java.io.File;
import java.nio.file.Files;
import jenkins.security.MasterToSlaveCallable; import jenkins.security.MasterToSlaveCallable;
import java.io.FileOutputStream; import java.io.FileOutputStream;
...@@ -13,7 +15,7 @@ public class SUTester { ...@@ -13,7 +15,7 @@ public class SUTester {
SU.execute(StreamTaskListener.fromStdout(),"kohsuke","bogus",new MasterToSlaveCallable<Object, Throwable>() { SU.execute(StreamTaskListener.fromStdout(),"kohsuke","bogus",new MasterToSlaveCallable<Object, Throwable>() {
public Object call() throws Throwable { public Object call() throws Throwable {
System.out.println("Touching /tmp/x"); System.out.println("Touching /tmp/x");
new FileOutputStream("/tmp/x").close(); Files.newOutputStream(new File("/tmp/x").toPath()).close();
return null; return null;
} }
}); });
......
...@@ -33,6 +33,8 @@ import hudson.util.StreamTaskListener; ...@@ -33,6 +33,8 @@ import hudson.util.StreamTaskListener;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Arrays; import java.util.Arrays;
import static org.junit.Assert.*; import static org.junit.Assert.*;
import org.junit.Assume; import org.junit.Assume;
...@@ -71,8 +73,8 @@ public class TarArchiverTest { ...@@ -71,8 +73,8 @@ public class TarArchiverTest {
f.chmod(0644); f.chmod(0644);
int dirMode = dir.child("subdir").mode(); int dirMode = dir.child("subdir").mode();
dir.tar(new FileOutputStream(tar),"**/*"); dir.tar(Files.newOutputStream(tar.toPath()),"**/*");
dir.zip(new FileOutputStream(zip)); dir.zip(Files.newOutputStream(zip.toPath()));
FilePath e = dir.child("extract"); FilePath e = dir.child("extract");
...@@ -149,12 +151,12 @@ public class TarArchiverTest { ...@@ -149,12 +151,12 @@ public class TarArchiverTest {
File openFile = file; File openFile = file;
try { try {
openFile.createNewFile(); openFile.createNewFile();
FileOutputStream fos = new FileOutputStream(openFile); try (OutputStream fos = Files.newOutputStream(openFile.toPath())) {
for (int i = 0; !finish && i < 5000000; i++) { // limit the max size, just in case. for (int i = 0; !finish && i < 5000000; i++) { // limit the max size, just in case.
fos.write(0); fos.write(0);
// Thread.sleep(5); // Thread.sleep(5);
}
} }
fos.close();
} catch (Exception e) { } catch (Exception e) {
ex = e; ex = e;
} }
......
...@@ -5,6 +5,7 @@ import static org.junit.Assert.assertEquals; ...@@ -5,6 +5,7 @@ import static org.junit.Assert.assertEquals;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
...@@ -62,7 +63,7 @@ public class ZipArchiverTest { ...@@ -62,7 +63,7 @@ public class ZipArchiverTest {
try { try {
zipFile = File.createTempFile("test", ".zip"); zipFile = File.createTempFile("test", ".zip");
archiver = new ZipArchiver(new FileOutputStream(zipFile)); archiver = new ZipArchiver(Files.newOutputStream(zipFile.toPath()));
archiver.visit(tmpFile, "foo\\bar\\baz\\Test.txt"); archiver.visit(tmpFile, "foo\\bar\\baz\\Test.txt");
} catch (Exception e) { } catch (Exception e) {
......
...@@ -38,6 +38,7 @@ import java.io.File; ...@@ -38,6 +38,7 @@ import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
import org.junit.Assume; import org.junit.Assume;
...@@ -204,7 +205,7 @@ public class DirectoryBrowserSupportTest { ...@@ -204,7 +205,7 @@ public class DirectoryBrowserSupportTest {
File file = File.createTempFile("DirectoryBrowserSupport", "zipDownload"); File file = File.createTempFile("DirectoryBrowserSupport", "zipDownload");
file.delete(); file.delete();
Util.copyStreamAndClose(page.getInputStream(), new FileOutputStream(file)); Util.copyStreamAndClose(page.getInputStream(), Files.newOutputStream(file.toPath()));
return file; return file;
} }
......
...@@ -8,6 +8,8 @@ import com.gargoylesoftware.htmlunit.html.HtmlFormUtil; ...@@ -8,6 +8,8 @@ import com.gargoylesoftware.htmlunit.html.HtmlFormUtil;
import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.tools.JDKInstaller.DescriptorImpl; import hudson.tools.JDKInstaller.DescriptorImpl;
import java.io.InputStream;
import java.nio.file.Files;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
...@@ -54,8 +56,7 @@ public class JDKInstallerTest { ...@@ -54,8 +56,7 @@ public class JDKInstallerTest {
LOGGER.warning(f+" doesn't exist. Skipping JDK installation tests"); LOGGER.warning(f+" doesn't exist. Skipping JDK installation tests");
} else { } else {
Properties prop = new Properties(); Properties prop = new Properties();
FileInputStream in = new FileInputStream(f); try (InputStream in = Files.newInputStream(f.toPath())) {
try {
prop.load(in); prop.load(in);
String u = prop.getProperty("oracle.userName"); String u = prop.getProperty("oracle.userName");
String p = prop.getProperty("oracle.password"); String p = prop.getProperty("oracle.password");
...@@ -65,8 +66,6 @@ public class JDKInstallerTest { ...@@ -65,8 +66,6 @@ public class JDKInstallerTest {
DescriptorImpl d = j.jenkins.getDescriptorByType(DescriptorImpl.class); DescriptorImpl d = j.jenkins.getDescriptorByType(DescriptorImpl.class);
d.doPostCredential(u,p); d.doPostCredential(u,p);
} }
} finally {
in.close();
} }
} }
} }
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册