ファイル構造のコピー

2440 ワード

 
package file;
import java.io.*;
public class CopyFile
{
	public static void main(String[] args)
	{
		File sourceFile = new File("D:/ ");
		File targetFile = new File("F:/");
		copy(sourceFile, targetFile);

	}
	public static void copy(File sourceFile, File targetFile)
	{
		File tarpath = new File(targetFile, sourceFile.getName());
		if (sourceFile.isDirectory())// 
		{
			tarpath.mkdir();// 
			System.out.println(tarpath.getName()+" ");
			File[] dir = sourceFile.listFiles();// 
			for(File f:dir)
			{
				copy(f,tarpath);
			}
		} 
	}
}
 

コンテンツのコピー
package file;
import java.io.*;
public class CopyFile
{
	public static void main(String[] args) throws IOException
	{
		File sourceFile = new File("D:/ ");
		File targetFile = new File("F:/");
		copy(sourceFile, targetFile);

	}
	public static void copy(File sourceFile, File targetFile) throws IOException
	{
		if(sourceFile.exists()&&targetFile.exists())
		{
			File tarpath = new File(targetFile, sourceFile.getName());// 
			if (sourceFile.isDirectory())// 
			{
				tarpath.mkdir();// 
				System.out.println(" :"+tarpath.getName()+" ");
				File[] dir = sourceFile.listFiles();// 
				for(File f:dir)
				{
					copy(f,tarpath);
				}
			} 
			else
			{
				//tarpath.createNewFile();// 
				FileInputStream is=new FileInputStream(sourceFile);
				FileOutputStream os=new FileOutputStream(tarpath);
				BufferedInputStream bis=new BufferedInputStream(is);
				BufferedOutputStream bos=new BufferedOutputStream(os);
				int length=0;
				byte []bytes=new byte[4096];
				while((length=bis.read(bytes))!=-1)
				{
					bos.write(bytes, 0, length);
				}
				if(bis!=null)
				{
					bis.close();
				}
				if(bos!=null)
				{
					bos.close();
				}
				System.out.println(" :"+tarpath.getName()+" ");
			}
		}
		else
		{
			System.out.println(" ");
		}
	}
}