filecopy.java
字号:
import java.io.*;
class FileCopy
{
public static void main(String []args)
{
if(args.length !=2)
System.out.println("Usage:java FileCopy"+ "<Source File> <Dest File>");
else
{
try{
copy(args[0],args[1]);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
public static void copy(String srcfile, String dstfile) throws IOException
{
byte [] buf;
int bytes;
File src=new File(srcfile);
File dst=new File(dstfile);
FileInputStream srcs=null;
FileOutputStream dsts=null;
try
{
if(! src.exists() || ! src.isFile())
throw new FileCopyException("FileCopy"+"no such source File:"+srcfile);
if(!src.canRead())
throw new FileCopyException("FileCopy:"+"source file is unreadable:"+srcfile);
if(dst.exists())
{
if(dst.isFile())
{
if(! dst.canWrite())
throw new FileCopyException("FileCopy:"+"dest file is unWriteable:"+dstfile);
System.out.print("File"+dstfile+"already exists, OverWrite ?(Y/N):");
System.out.flush();
String resp=new DataInputStream(System.in).readLine();
if(!resp.equals("Y")&& !resp.equals("y"))
throw new FileCopyException("FileCopy:"+"copy cancelled.");
}
else
{
throw new FileCopyException("FileCopy:"+"dest is not a file:"+dstfile);
}
}
else
{
File parent=parent(dst);
if(!parent.exists())
throw new FileCopyException("FileCopy:"+"dest directory doesn't exists:"+dstfile);
if(!parent.canWrite())
throw new FileCopyException("FileCopy:"+"dest directory is unwriteable:"+dstfile);
}
srcs=new FileInputStream(src);
dsts=new FileOutputStream(dst);
buf=new byte[1024];
while((bytes=srcs.read(buf))!=-1)
dsts.write(buf,0,bytes);
}
finally
{
if(srcs !=null)
try
{
srcs.close();
}
catch(IOException e)
{
}
if(dsts !=null)
try
{
dsts.close();
}
catch(IOException e)
{
}
}
}
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("user.dir"));
}
return new File(dirname);
}
}
class FileCopyException extends IOException
{
public FileCopyException(String msg)
{
super(msg);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -