文件操作工具

public class FileUtil
{

	/**
	 * 私有构造什么也不做仅仅是为了不让别人直接创建一个FileUtil实例
	 */
	private FileUtil()
	{

	}

	/**
	 * 查询某个目录下指定扩展名的文件
	 * 
	 */
	public static String[] findByExt(String Dir, String extNameReg)
	{
		File f = new File(Dir);
		FilenameFilter ff = new MyFileFilter(extNameReg);
		return f.list(ff);
	}

	/**
	 * 显示文件的内容
	 * 
	 */
	public static void showFile(String fileName)
	{
		StringBuffer sb = new StringBuffer(0);
		BufferedReader br = null;
		try
		{
			File f = new File(fileName);
			if (f.isFile())
			{
				sb.append(fileName).append("\r\n");
				FileReader fr = new FileReader(f);
				br = new BufferedReader(fr);
				String str = br.readLine();
				while (str != null)
				{
					sb.append(str).append("\r\n");
					str = br.readLine();
				}
				System.out.println(sb);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (null != br)
			{
				try
				{
					br.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 复制文件
	 * 
	 */
	public static void copyFile(String srcPath, String desPath)
	{
		try
		{
			File srcf = new File(srcPath);
			if (srcf.exists())
			{
				FileInputStream inStream = new FileInputStream(srcPath);
				FileOutputStream outStream = new FileOutputStream(desPath);
				byte[] buffer = new byte[1024];
				// 返回实际读取到文件内容的长度
				int length = inStream.read(buffer);
				while (length != -1)
				{
					// 如果不指定写入的文件长度,文件大小会超出复制的文件
					outStream.write(buffer, 0, length);
					length = inStream.read(buffer);
				}
				inStream.close();
				outStream.close();
			}
			else
			{
				System.out.println("源文件" + srcPath + "不存在!");
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 移动文件
	 * 
	 */
	public static void moveFile(String srcPath, String desPath)
	{
		try
		{
			copyFile(srcPath, desPath);
			File f = new File(srcPath);
			if (f.exists())
			{
				f.delete();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件
	 * 
	 */
	public static void delFile(String filePath)
	{
		try
		{
			File f = new File(filePath);
			if (f.exists())
			{
				f.delete();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

class MyFileFilter implements FilenameFilter
{
	private Pattern pattern;

	MyFileFilter(String regex)
	{
		pattern = Pattern.compile(regex);
	}

	public boolean accept(File dir, String name)
	{
		String nameString = new File(name).getName();
		String extName = nameString.substring(nameString.lastIndexOf(".") + 1);
		return pattern.matcher(extName).matches();
	}

}

 

你可能感兴趣的:(F#)