在项目测试的时候,有一个需求,需要频繁的将报文丢到通道测试结果,因此写下了这个方法再此做记录
原理:
使用线程反复监控桌面的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
下载的类里,最后一段代码是没用的,可以删掉。