⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filecopy.java

📁 本书属于《开发专家之 Sun ONE》系列丛书
💻 JAVA
字号:
//FileCopy.java
//自定义异常
class FileCopyException extends IOException
{
	public FileCopyException(String msg)
	{
		//调用父类的构造函数
		super(msg);
	}
}
//FileCopy类
public class FileCopy
{
	public static void copy(String sourcename,String destname) 
throw IOException
	{
		//创建源文件对象
		File sourcefile = new File(sourcename);
		//创建目标文件对象
		File destfile   = new File(destname);
		//定义文件输入流
		FileInputStream   source= null;
		//定义文件输出流
		FileOutputStream  dest = null;
		byte[] buffer;
		int    readbytes;

		try
		{
			//判断文件十分存在、是否为普通文件
	if(!sourcefile.exists() || !sourcefile.isFile())
				throw new FileCopyException("No such file:"+sourcename+"\n");
			//判断是否具有写权限
			if(!sourcefile.canRead())
				throw new FileCopyException(sourcename+"cann't be read\n");
			//判断目标文件存在
			if(destfile.exists())
			{
				//目标文件是普通文件
				if(destfile.isFile())
				{
					//定义数据输入流
					DataInputStream in = new DataInputStream(System.in);
					String response;
					if(!destfile.canWrite())throw new
 FileCopyException(destname+"does not can write\n");
					System.out.println("Overwrite (Yes/No) ?");
					System.out.flush();
					//读取输入内容
					response = System.in.readline();
				}
				else
				{
					System.out.println("不能对目录进行读写");
				}
			}
			else
			{
				System.out.println("指定的文件不存在");
			}
			//创建文件输入对象
			source = new FileInputStream(sourcefile);
			//创建文件输出对象
			destination = new FileOutputStream(destfile);

			buffer = new byte[1024];
			//文件输出
			for(;;)
			{
				readbytes = source.read(buffer);
				if(readbytes==-1)break;
				destination.write(buffer,0,readbytes);
			}
		}
		finally
		{
			if(source!=null)
			{
				try
				{
					source.close();
				}
				catch(IOException e){};
			}
			if(destination!=null)
			{
				try
				{
					destination.close();
				}
				catch(IOException e){};
			}
		}
	}
	public static void main(String args[])
	{
		if(args.length!=2)
			System.out.println("java FileCopy <SourceFile> <DestFile>");
		else
		{
			try
			{
				copy(args[0],args[1]);
			}
			catch(IOException e)
			{
				System.out.println(e.getMessage());
			}
		}
	}
	
	private static File parent(File f)
	{
		String dirname = f.getParent();
			if(f.isAbsolute())
				return new File(File.seperator);
			else
				return new File(System.getProperty("user.dir"));
	}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -