1. 程式人生 > >巢狀刪除多級目錄, 刪除單級目錄, 建立多級目錄, 複製檔案

巢狀刪除多級目錄, 刪除單級目錄, 建立多級目錄, 複製檔案

備一份自己用:

	/**
	 * 巢狀刪除多級目錄
	 * 
	 * @param[in] oPath 目錄
	 */
	private static void deleteFolder(final File oPath)
	{
		final File[] dirs = oPath.listFiles();
		if (dirs != null)
		{
			for (final File oSubPath : dirs)
			{
				if (oSubPath.isDirectory())
				{
					deleteFolder(oSubPath);
				}
			}
		}
		oPath.delete();
	}

	/**
	 * 刪除單級目錄
	 * 
	 * @param[in] sPath 目錄
	 */
	public static void deleteFolder(final String sPath)
	{
		final File oPath = new File(sPath);
		if (!oPath.exists() || !oPath.isDirectory())
		{
			return;
		}

		deleteFolder(oPath);
	}

	/**
	 * 建立多級目錄
	 * 
	 * @param[in] sPath 目錄
	 * @return 是否建立成功
	 */
	public static boolean createFolder(final String sPath)
	{
		try
		{
			final File oPath = new File(sPath);
			if (!oPath.exists())
			{
				oPath.mkdirs();
			}
			return true;
		}
		catch (final Exception e)
		{
			return false;
		}
	}

	/**
	 * 複製檔案
	 * 
	 * @param[in] sFile1
	 * @param[in] sFile2
	 * @throws IOException
	 */
	public static void copyFile(final String sFile1, final String sFile2) throws IOException
	{
		final File oFile1 = new File(sFile1);
		if (oFile1.exists())
		{
			final String sPath = sFile2.substring(0, sFile2.lastIndexOf('\\'));
			createFolder(sPath); // 確保目標目錄存在

			final File oFile2 = new File(sFile2);
			final RandomAccessFile inData = new RandomAccessFile(oFile1, "r");
			final RandomAccessFile opData = new RandomAccessFile(oFile2, "rw");
			final FileChannel inChannel = inData.getChannel();
			final FileChannel opChannel = opData.getChannel();
			inChannel.transferTo(0, inChannel.size(), opChannel);
			//=========================上一行程式碼與下面的程式碼功能相同=========================
			//			final long size = inChannel.size();
			//			final MappedByteBuffer buf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
			//			opChannel.write(buf);
			//=================================================================
			inChannel.close();
			inData.close();
			opChannel.close();
			opData.close();
		}
	}