JAVA监视某文件夹并对文件夹里的文件做操作

在项目测试的时候,有一个需求,需要频繁的将报文丢到通道测试结果,因此写下了这个方法再此做记录

原理:

使用线程反复监控桌面的temp文件夹,如果此时有文件为xml被丢进来,就将xml放入流中并将它发送出去,这里用到了自定义过滤,使用很简单一看就懂。最后,将temp的文件删除掉。这样测试起来,已经非常方便了。
public class Listener
{
	public static String tempDir = "C:/Users/admin/Desktop/temp/";

	public static void main(String[] args) throws Exception
	{
		File tempPath = new File(tempDir);
		if (!tempPath.exists())
		{
			tempPath.mkdirs();
		}
		Runnable runnable = new Runnable()
		{
			public void run()
			{
				File file = new File(tempDir);
				File[] fs = file.listFiles(filter);
				if (fs.length != 0)
				{
					for (int i = 0; i < fs.length; i++)
					{
						copyFile(fs[i]);
					}
				}
			}
		};
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		// 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
		service.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.SECONDS);
	}

	public static void copyFile(File fromFile)
	{
		String str;
		FileInputStream ins;
		try
		{
			ins = new FileInputStream(fromFile);

			byte[] buffer = new byte[ins.available()];
			ins.read(buffer);
			ins.close();
			str = new String(buffer, "UTF-8");
			System.out.println(str);
			MessageUtils.sendMsg(str);
			fromFile.delete();
		} catch (FileNotFoundException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 自定义过滤
	 * 
	 * @author admin
	 */
	static FileFilter filter = new FileFilter()
	{
		@Override
		public boolean accept(File pathname)
		{
			String filename = pathname.getName().toLowerCase();
			if (filename.contains(".xml"))
			{
				return true;
			} else
			{
				return false;
			}
		}
	};
}

http://download.csdn.net/download/u012552275/9815571
下载的类里,最后一段代码是没用的,可以删掉。


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值