kingasa
asked on
copy file
Hello
How do I copy file from one directory to another
thanks ASA.
How do I copy file from one directory to another
thanks ASA.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
just a note: it seems to me better to use directly Input/OutputStreams and byte[], instead of Reader&Writers & char[] ...
this is another solution
import java.io.*;
public class FileCopy {
public static void copy(String source_name, String dest_name)
throws IOException
{
File source_file = new File(source_name);
File destination_file = new File(dest_name);
FileInputStream source = null;
FileOutputStream destination = null;
byte[] buffer;
int bytes_read;
try {
// First make sure the specified source file
// exists, is a file, and is readable.
if (!source_file.exists() || !source_file.isFile())
throw new FileCopyException("FileCop y: no such source file: " + source_name);
if (!source_file.canRead())
throw new FileCopyException("FileCop y: source file " +
"is unreadable: " + source_name);
// If the destination exists, make sure it is a writeable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writeable.
if (destination_file.exists() ) {
if (destination_file.isFile() ) {
DataInputStream in = new DataInputStream(System.in) ;
String response;
if (!destination_file.canWrit e())
throw new FileCopyException("FileCop y:
destination " +
"file is unwriteable: " + dest_name);
System.out.print("File " + dest_name +
" already exists. Overwrite? (Y/N): ");
System.out.flush();
response = in.readLine();
if (!response.equals("Y") && !response.equals("y"))
throw new FileCopyException("FileCop y: copy
cancelled.");
}
else
throw new FileCopyException("FileCop y: destination "
+ "is not a file: " + dest_name);
}
else {
File parentdir = parent(destination_file);
if (!parentdir.exists())
throw new FileCopyException("FileCop y: destination "
+ "directory doesn't exist: " +
dest_name);
if (!parentdir.canWrite())
throw new FileCopyException("FileCop y: destination "
+ "directory is unwriteable: " +
dest_name);
}
// If we've gotten this far, then everything is okay; we can
// copy the file.
source = new FileInputStream(source_fil e);
destination = new FileOutputStream(destinati on_file);
buffer = new byte[1024];
while(true) {
bytes_read = source.read(buffer);
if (bytes_read == -1) break;
destination.write(buffer, 0, bytes_read);
}
}
// No matter what happens, always close any streams we've
opened.
finally {
if (source != null)
try { source.close(); } catch (IOException e) { ; }
if (destination != null)
try { destination.close(); } catch (IOException e) { ; }
}
}
// File.getParent() can return null when the file is specified
without
// a directory or is in the root directory.
// This method handles those cases.
private static File parent(File f) {
String dirname = f.getParent();
if (dirname == null) {
if (f.isAbsolute()) return new File(File.separator);
else return new File(System.getProperty("u ser.dir")) ;
}
return new File(dirname);
}
public static void main(String[] args) {
if (args.length != 2)
System.err.println("Usage: java FileCopy " +
"<source file> <destination file>");
else {
try { copy(args[0], args[1]); }
catch (IOException e) {
System.err.println(e.getMe ssage()); }
}
}
}
class FileCopyException extends IOException {
public FileCopyException(String msg) { super(msg); }
}
mb...
import java.io.*;
public class FileCopy {
public static void copy(String source_name, String dest_name)
throws IOException
{
File source_file = new File(source_name);
File destination_file = new File(dest_name);
FileInputStream source = null;
FileOutputStream destination = null;
byte[] buffer;
int bytes_read;
try {
// First make sure the specified source file
// exists, is a file, and is readable.
if (!source_file.exists() || !source_file.isFile())
throw new FileCopyException("FileCop
if (!source_file.canRead())
throw new FileCopyException("FileCop
"is unreadable: " + source_name);
// If the destination exists, make sure it is a writeable file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writeable.
if (destination_file.exists()
if (destination_file.isFile()
DataInputStream in = new DataInputStream(System.in)
String response;
if (!destination_file.canWrit
throw new FileCopyException("FileCop
destination " +
"file is unwriteable: " + dest_name);
System.out.print("File " + dest_name +
" already exists. Overwrite? (Y/N): ");
System.out.flush();
response = in.readLine();
if (!response.equals("Y") && !response.equals("y"))
throw new FileCopyException("FileCop
cancelled.");
}
else
throw new FileCopyException("FileCop
+ "is not a file: " + dest_name);
}
else {
File parentdir = parent(destination_file);
if (!parentdir.exists())
throw new FileCopyException("FileCop
+ "directory doesn't exist: " +
dest_name);
if (!parentdir.canWrite())
throw new FileCopyException("FileCop
+ "directory is unwriteable: " +
dest_name);
}
// If we've gotten this far, then everything is okay; we can
// copy the file.
source = new FileInputStream(source_fil
destination = new FileOutputStream(destinati
buffer = new byte[1024];
while(true) {
bytes_read = source.read(buffer);
if (bytes_read == -1) break;
destination.write(buffer, 0, bytes_read);
}
}
// No matter what happens, always close any streams we've
opened.
finally {
if (source != null)
try { source.close(); } catch (IOException e) { ; }
if (destination != null)
try { destination.close(); } catch (IOException e) { ; }
}
}
// File.getParent() can return null when the file is specified
without
// a directory or is in the root directory.
// This method handles those cases.
private static File parent(File f) {
String dirname = f.getParent();
if (dirname == null) {
if (f.isAbsolute()) return new File(File.separator);
else return new File(System.getProperty("u
}
return new File(dirname);
}
public static void main(String[] args) {
if (args.length != 2)
System.err.println("Usage:
"<source file> <destination file>");
else {
try { copy(args[0], args[1]); }
catch (IOException e) {
System.err.println(e.getMe
}
}
}
class FileCopyException extends IOException {
public FileCopyException(String msg) { super(msg); }
}
mb...
static public void execCmd(String[] cmdParam) throws Exception {
StringBuffer cmd = new StringBuffer();
cmd.append(cmdParam[0]).ap pend(" ");
for(int i = 1; i<cmdParam.length; i++) {
cmd.append(cmdParam[i]).ap pend(" ");
}
Process pr = Runtime.getRuntime().exec( cmd.toStri ng());
pr.waitFor();
Log.logMsg("Exit Value for :" + cmd + " is " + pr.exitValue());
}
call this method lie execCmd(" cmd.exe /c copy source destinaltion")
hope this helps..
Akkaiah
StringBuffer cmd = new StringBuffer();
cmd.append(cmdParam[0]).ap
for(int i = 1; i<cmdParam.length; i++) {
cmd.append(cmdParam[i]).ap
}
Process pr = Runtime.getRuntime().exec(
pr.waitFor();
Log.logMsg("Exit Value for :" + cmd + " is " + pr.exitValue());
}
call this method lie execCmd(" cmd.exe /c copy source destinaltion")
hope this helps..
Akkaiah
The first solution hangs on zero-length files. With this change it doesn't.
int len;
while ((len = br.read(charBuff,0,fileLen gth)) > 0) bw.write(charBuff,0,len);
int len;
while ((len = br.read(charBuff,0,fileLen
Using the new Java IO, this becomes very fast and simple:
/** Fast & simple file copy. */
public static void copy(File source, File dest) throws IOException {
FileChannel in = null, out = null;
try {
in = new FileInputStream(source).ge tChannel() ;
out = new FileOutputStream(dest).get Channel();
long size = in.size();
MappedByteBuffer buf = in.map(FileChannel.MapMode .READ_ONLY , 0, size);
out.write(buf);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
This will even work if your files are larger than physical memory, but it may swap out a lot of pages you'd have rather kept in memory.
/** Fast & simple file copy. */
public static void copy(File source, File dest) throws IOException {
FileChannel in = null, out = null;
try {
in = new FileInputStream(source).ge
out = new FileOutputStream(dest).get
long size = in.size();
MappedByteBuffer buf = in.map(FileChannel.MapMode
out.write(buf);
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
This will even work if your files are larger than physical memory, but it may swap out a lot of pages you'd have rather kept in memory.
gforman++;
MappedByteBuffer keeps the input file open even after proper closing of channel...
Here is the way to solve this..
in = new FileInputStream(source).ge tChannel() ;
out = new FileOutputStream(dest).get Channel();
in.transferTo( 0, in.size(), out);
that's it :)
Here is the way to solve this..
in = new FileInputStream(source).ge
out = new FileOutputStream(dest).get
in.transferTo( 0, in.size(), out);
that's it :)
shiva_in++; shiva_in++;
Let's hear it for the power of collaboration/sharing (e.g. experts-exchange) & may the best ideas bubble to the top.
Let's hear it for the power of collaboration/sharing (e.g. experts-exchange) & may the best ideas bubble to the top.