嵌套删除多级目录, 删除单级目录, 创建多级目录, 复制文件

备一份自己用:

	/**
	 * 嵌套删除多级目录
	 * 
	 * @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();
		}
	}

你可能感兴趣的:(文件)