Java Tutorial/File/Copy
Содержание
- 1 Buffered copying
- 2 Buffered copying between source(InputStream, Reader, String and byte[]) and destinations (OutputStream, Writer, String and byte[]).
- 3 Copies all data from an input stream to an output stream.
- 4 Copies the contents of the Reader into the Writer, until the end of the stream has been reached.
- 5 Copy a directory and all of its contents.
- 6 Copy a file and user buffer
- 7 Copy chars from a Reader to a Writer.
- 8 copy Completely (InputStream input, OutputStream output)
- 9 copy Completely (Reader input, Writer output)
- 10 copy Completely(URI input, URI output)
- 11 Copy file and directory
- 12 Copy the source file system structure into the supplied target location.
Buffered copying
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
/**
* This class provides static utility methods for buffered
* copying between sources (<code>InputStream</code>, <code>Reader</code>,
* <code>String</code> and <code>byte[]</code>) and destinations
* (<code>OutputStream</code>, <code>Writer</code>, <code>String</code> and
* <code>byte[]</code>).
*
* Unless otherwise noted, these <code>copy</code> methods do <em>not</em>
* flush or close the streams. Often doing so would require making non-portable
* assumptions about the streams" origin and further use. This means that both
* streams" <code>close()</code> methods must be called after copying. if one
* omits this step, then the stream resources (sockets, file descriptors) are
* released when the associated Stream is garbage-collected. It is not a good
* idea to rely on this mechanism. For a good overview of the distinction
* between "memory management" and "resource management", see
* for a list of valid encoding types.
* @throws IOException In case of an I/O problem
*/
public static void copy(
InputStream input,
Writer output,
String encoding)
throws IOException {
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
// ----------------------------------------------------------------
// Reader -> OutputStream
// ----------------------------------------------------------------
/**
* Serialize chars from a <code>Reader</code> to bytes on an
* <code>OutputStream</code>, and flush the <code>OutputStream</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(
Reader input,
OutputStream output)
throws IOException {
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we
// have to flush here.
out.flush();
}
// ----------------------------------------------------------------
// String -> OutputStream
// ----------------------------------------------------------------
/**
* Serialize chars from a <code>String</code> to bytes on an
* <code>OutputStream</code>, and
* flush the <code>OutputStream</code>.
* @param input the <code>String</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(
String input,
OutputStream output)
throws IOException {
StringReader in = new StringReader(input);
OutputStreamWriter out = new OutputStreamWriter(output);
copy(in, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we
// have to flush here.
out.flush();
}
// ----------------------------------------------------------------
// String -> Writer
// ----------------------------------------------------------------
/**
* Copy chars from a <code>String</code> to a <code>Writer</code>.
* @param input the <code>String</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(String input, Writer output)
throws IOException {
output.write(input);
}
}
Buffered copying between source(InputStream, Reader, String and byte[]) and destinations (OutputStream, Writer, String and byte[]).
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
/**
*
* This class provides static utility methods for buffered
* copying between sources (<code>InputStream</code>, <code>Reader</code>, <code>String</code> and
* <code>byte[]</code>) and destinations (<code>OutputStream</code>, <code>Writer</code>,
* <code>String</code> and <code>byte[]</code>).
*
*
* Unless otherwise noted, these <code>copy</code> methods do <em>not</em> flush or close the
* streams. Often doing so would require making non-portable assumptions about the streams" origin
* and further use. This means that both streams" <code>close()</code> methods must be called after
* copying. if one omits this step, then the stream resources (sockets, file descriptors) are
* released when the associated Stream is garbage-collected. It is not a good idea to rely on this
* mechanism. For a good overview of the distinction between "memory management" and "resource
* management", see for a list of valid encoding types.
* @throws IOException In case of an I/O problem
*/
public static void copy(InputStream input, Writer output, String encoding) throws IOException
{
InputStreamReader in = new InputStreamReader(input, encoding);
copy(in, output);
}
/**
* Serialize chars from a <code>Reader</code> to bytes on an
* <code>OutputStream</code>, and flush the <code>OutputStream</code>.
* @param input the <code>Reader</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(Reader input, OutputStream output) throws IOException
{
OutputStreamWriter out = new OutputStreamWriter(output);
copy(input, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we have to flush here.
out.flush();
}
/**
* Serialize chars from a <code>String</code> to bytes on an <code>OutputStream</code>, and
* flush the <code>OutputStream</code>.
* @param input the <code>String</code> to read from
* @param output the <code>OutputStream</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(String input, OutputStream output) throws IOException
{
StringReader in = new StringReader(input);
OutputStreamWriter out = new OutputStreamWriter(output);
copy(in, out);
// XXX Unless anyone is planning on rewriting OutputStreamWriter, we have to flush here.
out.flush();
}
/**
* Copy chars from a <code>String</code> to a <code>Writer</code>.
* @param input the <code>String</code> to read from
* @param output the <code>Writer</code> to write to
* @throws IOException In case of an I/O problem
*/
public static void copy(String input, Writer output) throws IOException
{
output.write(input);
}
/**
* The name says it all.
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
}
Copies all data from an input stream to an output stream.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Copies all data from an input stream to an output stream.
*/
public class StreamPumper implements Runnable {
/** the default size of the internal buffer for copying the streams */
private static final int DEFAULT_SIZE = 1024;
/** the input stream to pump from */
private final InputStream is;
/** the output stream to pmp into */
private final OutputStream os;
/** the size of the internal buffer for copying the streams */
private final int size;
/** was the end of the stream reached */
private boolean finished;
/** close the output stream when exhausted */
private final boolean closeWhenExhausted;
/**
* Create a new stream pumper.
*
* @param is
* input stream to read data from
* @param os
* output stream to write data to.
* @param closeWhenExhausted
* if true, the output stream will be closed when the input is
* exhausted.
*/
public StreamPumper(final InputStream is, final OutputStream os, final boolean closeWhenExhausted) {
this.is = is;
this.os = os;
this.size = DEFAULT_SIZE;
this.closeWhenExhausted = closeWhenExhausted;
}
/**
* Create a new stream pumper.
*
* @param is
* input stream to read data from
* @param os
* output stream to write data to.
* @param closeWhenExhausted
* if true, the output stream will be closed when the input is
* exhausted.
* @param size
* the size of the internal buffer for copying the streams
*/
public StreamPumper(final InputStream is, final OutputStream os,
final boolean closeWhenExhausted, final int size) {
this.is = is;
this.os = os;
this.size = (size > 0 ? size : DEFAULT_SIZE);
this.closeWhenExhausted = closeWhenExhausted;
}
/**
* Create a new stream pumper.
*
* @param is
* input stream to read data from
* @param os
* output stream to write data to.
*/
public StreamPumper(final InputStream is, final OutputStream os) {
this(is, os, false);
}
/**
* Copies data from the input stream to the output stream. Terminates as soon
* as the input stream is closed or an error occurs.
*/
public void run() {
synchronized (this) {
// Just in case this object is reused in the future
finished = false;
}
final byte[] buf = new byte[this.size];
int length;
try {
while ((length = is.read(buf)) > 0) {
os.write(buf, 0, length);
}
} catch (Exception e) {
String msg = "Got exception while reading/writing the stream";
System.out.println(msg);
} finally {
if (closeWhenExhausted) {
try {
os.close();
} catch (IOException e) {
String msg = "Got exception while closing exhausted output stream";
System.out.println(msg);
}
}
synchronized (this) {
finished = true;
notifyAll();
}
}
}
/**
* Tells whether the end of the stream has been reached.
*
* @return true is the stream has been exhausted.
*/
public synchronized boolean isFinished() {
return finished;
}
/**
* This method blocks until the stream pumper finishes.
*
* @see #isFinished()
*/
public synchronized void waitFor() throws InterruptedException {
while (!isFinished()) {
wait();
}
}
}
Copies the contents of the Reader into the Writer, until the end of the stream has been reached.
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------
* IOUtils.java
* ------------
* (C)opyright 2002-2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* $Id: IOUtils.java,v 1.8 2009/01/22 08:34:58 taqua Exp $
*
* Changes
* -------
* 26-Jan-2003 : Initial version
* 23-Feb-2003 : Documentation
* 25-Feb-2003 : Fixed Checkstyle issues (DG);
* 29-Apr-2003 : Moved to jcommon
* 04-Jan-2004 : Fixed JDK 1.2.2 issues with createRelativeURL;
* added support for query strings within these urls (TM);
*/
/**
* The IOUtils provide some IO related helper methods.
*
* @author Thomas Morgner.
*/
public class Main {
/**
* Copies the contents of the Reader into the Writer, until the end of the
* stream has been reached.
*
* @param in the reader from which to read.
* @param out the writer where the data is written to.
* @param buffersize the buffer size.
*
* @throws IOException if a IOError occurs.
*/
public void copyWriter(final Reader in, final Writer out,
final int buffersize)
throws IOException {
// create a 4kbyte buffer to read the file
final char[] bytes = new char[buffersize];
// the input stream does not supply accurate available() data
// the zip entry does not know the size of the data
int bytesRead = in.read(bytes);
while (bytesRead > -1) {
out.write(bytes, 0, bytesRead);
bytesRead = in.read(bytes);
}
}
}
Copy a directory and all of its contents.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
Derby - Class org.apache.derby.iapi.util.PropertyUtil
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Main {
private static final int BUFFER_SIZE = 4096 * 4;
/**
* Copy a directory and all of its contents.
*/
public static boolean copyDirectory(File from, File to) {
return copyDirectory(from, to, (byte[]) null, (String[]) null);
}
public static boolean copyDirectory(String from, String to) {
return copyDirectory(new File(from), new File(to));
}
/**
* @param filter -
* array of names to not copy.
*/
public static boolean copyDirectory(File from, File to, byte[] buffer, String[] filter) {
//
// System.out.println("copyDirectory("+from+","+to+")");
if (from == null)
return false;
if (!from.exists())
return true;
if (!from.isDirectory())
return false;
if (to.exists()) {
// System.out.println(to + " exists");
return false;
}
if (!to.mkdirs()) {
// System.out.println("can"t make" + to);
return false;
}
String[] list = from.list();
// Some JVMs return null for File.list() when the
// directory is empty.
if (list != null) {
if (buffer == null)
buffer = new byte[BUFFER_SIZE]; // reuse this buffer to copy files
nextFile: for (int i = 0; i < list.length; i++) {
String fileName = list[i];
if (filter != null) {
for (int j = 0; j < filter.length; j++) {
if (fileName.equals(filter[j]))
continue nextFile;
}
}
File entry = new File(from, fileName);
// System.out.println("\tcopying entry " + entry);
if (entry.isDirectory()) {
if (!copyDirectory(entry, new File(to, fileName), buffer, filter))
return false;
} else {
if (!copyFile(entry, new File(to, fileName), buffer))
return false;
}
}
}
return true;
}
public static boolean copyFile(File from, File to) {
return copyFile(from, to, (byte[]) null);
}
public static boolean copyFile(File from, File to, byte[] buf) {
if (buf == null)
buf = new byte[BUFFER_SIZE];
//
// System.out.println("Copy file ("+from+","+to+")");
FileInputStream from_s = null;
FileOutputStream to_s = null;
try {
from_s = new FileInputStream(from);
to_s = new FileOutputStream(to);
for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf))
to_s.write(buf, 0, bytesRead);
from_s.close();
from_s = null;
to_s.getFD().sync(); // RESOLVE: sync or no sync?
to_s.close();
to_s = null;
} catch (IOException ioe) {
return false;
} finally {
if (from_s != null) {
try {
from_s.close();
} catch (IOException ioe) {
}
}
if (to_s != null) {
try {
to_s.close();
} catch (IOException ioe) {
}
}
}
return true;
}
}
Copy a file and user buffer
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
Derby - Class org.apache.derby.iapi.util.PropertyUtil
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class Main {
private static final int BUFFER_SIZE = 4096 * 4;
/**
* Copy a directory and all of its contents.
*/
public static boolean copyDirectory(File from, File to) {
return copyDirectory(from, to, (byte[]) null, (String[]) null);
}
public static boolean copyDirectory(String from, String to) {
return copyDirectory(new File(from), new File(to));
}
/**
* @param filter -
* array of names to not copy.
*/
public static boolean copyDirectory(File from, File to, byte[] buffer, String[] filter) {
//
// System.out.println("copyDirectory("+from+","+to+")");
if (from == null)
return false;
if (!from.exists())
return true;
if (!from.isDirectory())
return false;
if (to.exists()) {
// System.out.println(to + " exists");
return false;
}
if (!to.mkdirs()) {
// System.out.println("can"t make" + to);
return false;
}
String[] list = from.list();
// Some JVMs return null for File.list() when the
// directory is empty.
if (list != null) {
if (buffer == null)
buffer = new byte[BUFFER_SIZE]; // reuse this buffer to copy files
nextFile: for (int i = 0; i < list.length; i++) {
String fileName = list[i];
if (filter != null) {
for (int j = 0; j < filter.length; j++) {
if (fileName.equals(filter[j]))
continue nextFile;
}
}
File entry = new File(from, fileName);
// System.out.println("\tcopying entry " + entry);
if (entry.isDirectory()) {
if (!copyDirectory(entry, new File(to, fileName), buffer, filter))
return false;
} else {
if (!copyFile(entry, new File(to, fileName), buffer))
return false;
}
}
}
return true;
}
public static boolean copyFile(File from, File to) {
return copyFile(from, to, (byte[]) null);
}
public static boolean copyFile(File from, File to, byte[] buf) {
if (buf == null)
buf = new byte[BUFFER_SIZE];
//
// System.out.println("Copy file ("+from+","+to+")");
FileInputStream from_s = null;
FileOutputStream to_s = null;
try {
from_s = new FileInputStream(from);
to_s = new FileOutputStream(to);
for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf))
to_s.write(buf, 0, bytesRead);
from_s.close();
from_s = null;
to_s.getFD().sync(); // RESOLVE: sync or no sync?
to_s.close();
to_s = null;
} catch (IOException ioe) {
return false;
} finally {
if (from_s != null) {
try {
from_s.close();
} catch (IOException ioe) {
}
}
if (to_s != null) {
try {
to_s.close();
} catch (IOException ioe) {
}
}
}
return true;
}
}
Copy chars from a Reader to a Writer.
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class Main {
/**
* Copy chars from a <code>Reader</code> to a <code>Writer</code>.
*
* This method buffers the input internally, so there is no need to use a
* <code>BufferedReader</code>.
*
* @param input
* the <code>Reader</code> to read from
* @param output
* the <code>Writer</code> to write to
* @return the number of characters copied
* @throws NullPointerException
* if the input or output is null
* @throws IOException
* if an I/O error occurs
* @since 1.1
*/
public static int copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[1024];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
}
copy Completely (InputStream input, OutputStream output)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class Main {
public static void copyCompletely(InputStream input, OutputStream output) throws IOException {
// if both are file streams, use channel IO
if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) {
try {
FileChannel target = ((FileOutputStream) output).getChannel();
FileChannel source = ((FileInputStream) input).getChannel();
source.transferTo(0, Integer.MAX_VALUE, target);
source.close();
target.close();
return;
} catch (Exception e) { /* failover to byte stream version */
}
}
byte[] buf = new byte[8192];
while (true) {
int length = input.read(buf);
if (length < 0)
break;
output.write(buf, 0, length);
}
try {
input.close();
} catch (IOException ignore) {
}
try {
output.close();
} catch (IOException ignore) {
}
}
}
copy Completely (Reader input, Writer output)
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class Main {
public static void copyCompletely(Reader input, Writer output)
throws IOException
{
char[] buf = new char[8192];
while (true)
{
int length = input.read(buf);
if (length < 0)
break;
output.write(buf, 0, length);
}
try { input.close(); } catch (IOException ignore) {}
try { output.close(); } catch (IOException ignore) {}
}
}
copy Completely(URI input, URI output)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.channels.FileChannel;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
public class Main {
public static void copyCompletely(URI input, URI output)
throws IOException
{
try
{
InputStream in = null;
try
{
File f = new File(input);
if (f.exists())
in = new FileInputStream(f);
}
catch (Exception notAFile)
{}
File out = new File(output);
File dir = out.getParentFile();
dir.mkdirs();
if (in == null)
in = input.toURL().openStream();
copyCompletely(in, new FileOutputStream(out));
}
catch (IllegalArgumentException e)
{
throw new IOException("Cannot copy to " + output);
}
}
public static void copyCompletely(InputStream input, OutputStream output) throws IOException {
// if both are file streams, use channel IO
if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) {
try {
FileChannel target = ((FileOutputStream) output).getChannel();
FileChannel source = ((FileInputStream) input).getChannel();
source.transferTo(0, Integer.MAX_VALUE, target);
source.close();
target.close();
return;
} catch (Exception e) { /* failover to byte stream version */
}
}
byte[] buf = new byte[8192];
while (true) {
int length = input.read(buf);
if (length < 0)
break;
output.write(buf, 0, length);
}
try {
input.close();
} catch (IOException ignore) {
}
try {
output.close();
} catch (IOException ignore) {
}
}
}
Copy file and directory
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
*
* FileUtils is a collection of routines for common file system operations.
*
* @author Dan Jemiolo (danj)
*
*/
public final class FileUtils {
/**
*
* The application"s current working directory.
*
*/
public static final File CURRENT_DIR = new File(".");
/**
*
* Copies the first file or directory to the second file or directory. <br>
* <br>
* If the first parameter is a file and the second is a file, then the method
* copies the contents of the first file into the second. If the second file
* does not exist, it is created. <br>
* <br>
* If the first parameter is a file and the second is a directory, the file is
* copied to the directory, overwriting any existing copy. <br>
* <br>
* If the first parameter is a directory and the second is a directory, the
* first is copied underneath the second. <br>
* <br>
* If the first parameter is a directory and the second is a file name or does
* not exist, a directory with that name is created, and the contents of the
* first directory are copied there.
*
* @param source
* @param destination
*
* @throws IOException
* <ul>
* <li>If the source does not exist.</li>
* <li>If the user does not have permission to modify the
* destination.</li>
* <li>If the copy fails for some reason related to system I/O.</li>
* </ul>
*
*/
public static void copy(File source, File destination) throws IOException {
if (source == null)
throw new NullPointerException("NullSource");
if (destination == null)
throw new NullPointerException("NullDestination");
if (source.isDirectory())
copyDirectory(source, destination);
else
copyFile(source, destination);
}
public static void copyDirectory(File source, File destination) throws IOException {
copyDirectory(source, destination, null);
}
public static void copyDirectory(File source, File destination, FileFilter filter)
throws IOException {
File nextDirectory = new File(destination, source.getName());
//
// create the directory if necessary...
//
if (!nextDirectory.exists() && !nextDirectory.mkdirs()) {
Object[] filler = { nextDirectory.getAbsolutePath() };
String message = "DirCopyFailed";
throw new IOException(message);
}
File[] files = source.listFiles();
//
// and then all the items below the directory...
//
for (int n = 0; n < files.length; ++n) {
if (filter == null || filter.accept(files[n])) {
if (files[n].isDirectory())
copyDirectory(files[n], nextDirectory, filter);
else
copyFile(files[n], nextDirectory);
}
}
}
public static void copyFile(File source, File destination) throws IOException {
//
// if the destination is a dir, what we really want to do is create
// a file with the same name in that dir
//
if (destination.isDirectory())
destination = new File(destination, source.getName());
FileInputStream input = new FileInputStream(source);
copyFile(input, destination);
}
public static void copyFile(InputStream input, File destination) throws IOException {
OutputStream output = null;
output = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int bytesRead = input.read(buffer);
while (bytesRead >= 0) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
input.close();
output.close();
}
}
Copy the source file system structure into the supplied target location.
/*
* JBoss DNA (http://www.jboss.org/dna)
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
* See the AUTHORS.txt file in the distribution for a full listing of
* individual contributors.
*
* JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
* is licensed to you under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* JBoss DNA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class FileMonitor {
/**
* Copy the source file system structure into the supplied target location. If
* the source is a file, the destiniation will be created as a file; if the
* source is a directory, the destination will be created as a directory.
*
* @param sourceFileOrDirectory
* the file or directory whose contents are to be copied into the
* target location
* @param destinationFileOrDirectory
* the location where the copy is to be placed; does not need to
* exist, but if it does its type must match that of <code>src</code>
* @return the number of files (not directories) that were copied
* @throws IllegalArgumentException
* if the <code>src</code> or <code>dest</code> references are
* null
* @throws IOException
*/
public static int copy(File sourceFileOrDirectory, File destinationFileOrDirectory)
throws IOException {
int numberOfFilesCopied = 0;
if (sourceFileOrDirectory.isDirectory()) {
destinationFileOrDirectory.mkdirs();
String list[] = sourceFileOrDirectory.list();
for (int i = 0; i < list.length; i++) {
String dest1 = destinationFileOrDirectory.getPath() + File.separator + list[i];
String src1 = sourceFileOrDirectory.getPath() + File.separator + list[i];
numberOfFilesCopied += copy(new File(src1), new File(dest1));
}
} else {
InputStream fin = new FileInputStream(sourceFileOrDirectory);
fin = new BufferedInputStream(fin);
try {
OutputStream fout = new FileOutputStream(destinationFileOrDirectory);
fout = new BufferedOutputStream(fout);
try {
int c;
while ((c = fin.read()) >= 0) {
fout.write(c);
}
} finally {
fout.close();
}
} finally {
fin.close();
}
numberOfFilesCopied++;
}
return numberOfFilesCopied;
}
}