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

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

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