定时器下利用轮询技术
我们目前仅仅做了一个关于轮询读文件写文件的方式
首先我们要明白定时器的方法,然后我们就可以实现定时发出询问,看文件夹中有那些文件读出它,能简单的做到实时的操作写到文件中的内容
1、先看定时器
1 Timer timer = new Timer(); 2 //调度读取、删除文件的定时器,第一个参数是指被调度的任务、第二个参数是指延迟多少毫秒、第三个参数是指间隔多少执行任务 3 timer.schedule(new lxTask(), 300, 2000);
上面注释的部分就简单的介绍了我们写入的参数,所以我们接下来写文件、读文件都将写在lxTask()类中
2、读、删文件
1 public class lxTask extends TimerTask{ 2 //在线程中用 3 public void run() { 4 List<File> files = readFile("e:/Test/"); //先指定文件夹路径下的文件 5 for (File file : files) { 6 try { 7 //获得该文件输入流 8 InputStream is = new FileInputStream(new File("e:/Test/"+file.getName())); 9 byte b[] = new byte[Integer.parseInt(new File("e:/Test/"+file.getName()).length() + "")]; 10 is.read(b); 11 is.close(); 12 //拼接本地路径,找到文件 13 String pString = "e:/Test/"+file.getName(); 14 //删除该文件 15 File f = new File(pString); 16 f.delete(); 17 } catch (FileNotFoundException e) { 18 e.printStackTrace(); 19 } catch (IOException e) { 20 e.printStackTrace(); 21 } 22 } 23 } 24 }
写文件
1 public class xlTask extends TimerTask{ 2 public void run() { 3 //写文件,固定文件名,当然也可以使用list写入多个文件名 4 File Path = new File("e:/Test/A.txt"); 5 if (!Path.exists() || !Path.isFile()) { 6 try { 7 Path.createNewFile(); 8 } catch (IOException e) { 9 e.printStackTrace(); 10 } 11 } 12 try { 13 PrintWriter pw = new PrintWriter(Path); 14 //具体往文件写什么 15 pw.write("=====写入====="); 16 pw.close(); 17 } catch (FileNotFoundException e) { 18 e.printStackTrace(); 19 } 20 } 21 }
此时我们简单的轮询写、删、读文件就完成了,当然,这些方法可能有缺陷和不适用的地方