//定时器 package ThreadTime; import java.util.Calendar; import java.util.Date; import java.util.Timer; import java.util.TimerTask; public class Time{ public static void main(String[] args){ //建立Timer类对象implements Runnable Timer t = new Timer(); // 定义任务 MyTask myTask = new MyTask(); // 设置任务的执行,5秒后开始,每5秒重复调用一次 t.schedule(myTask, 5000, 5000); } public static void timer1() { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { System.out.println("-------设定要指定任务--------"); } }, 2000);// 设定指定的时间time,此处为2000毫秒 } public static void timer2() { Timer timer = new Timer(); timer.schedule(new TimerTask() { public void run() { System.out.println("-------设定要指定任务--------"); } }, 1000, 5000); } public static void timer3() { Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println("-------设定要指定任务--------"); } }, 1000, 2000); } public static void timer4() { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 12); // 控制时 calendar.set(Calendar.MINUTE, 0); // 控制分 calendar.set(Calendar.SECOND, 0); // 控制秒 Date time = calendar.getTime(); // 得出执行任务的时间,此处为今天的12:00:00 Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { public void run() { System.out.println("-------设定要指定任务--------"); } }, time, 1000 * 60 * 60 * 24);// 这里设定将延时每天固定执行 } } ----------------------------------- package ThreadTime; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import mytest.OprationxmlVO; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import PDFTest.CreatePdfVO; import com.tecsun.framework.unitl.Report; public class MyTask extends TimerTask{ //TimeRun timeRun = new TimeRun(); public void run(){ try { isJudge("D:/test"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void isJudge(String path) throws IOException, SQLException, ClassNotFoundException{ //获取该文件夹下的 File file=new File(path); File[] tempList = file.listFiles(); System.out.println("该目录下对象个数:"+tempList.length); InputStream fis = null; //把图片编码 BASE64Encoder encoder = new BASE64Encoder(); File [] files = file.listFiles(); OutputStream outputStream=new FileOutputStream("D:/test/photo.txt"); for (int i = 0; i < tempList.length; i++) { fis = new FileInputStream(tempList[i]); //imageByteArray= IOUtils.toByteArray(fis); byte[] imageByteArray = new byte[fis.available()]; fis.read(imageByteArray); encoder.encode(imageByteArray); //System.out.println("字节流:"+encoder); try{ if (tempList[i].isFile()) { //System.out.println("文 件:"+tempList[i]); String fileName = tempList[i].getName(); //当文件是图片文件时将图片转换成64位字节流,然后读入photo.txt if(fileName.trim().toLowerCase().endsWith(".png")||fileName.trim().toLowerCase().endsWith(".jpg")||fileName.trim().toLowerCase().endsWith(".jpeg")) { //System.out.println("是图片"+i+"文件"+String.valueOf(encoder)); // outputStream.write(imageByteArray); //删除所有的图片 /*File fDel = new File(fileName); fDel.delete();*/ //txtRead(); } //当文件是.xml文件时 if(fileName.trim().toLowerCase().endsWith(".xml")) { //System.out.println("是图片"+i+".xml文件"+fileName); if(fileName.equals("operationxml.xml")){ //数据写入excel //xmlRead_writeExcel(fileName); //数据写入PDF System.out.println("fileName:--------------------"+fileName); xmlRead_writePdf(fileName,"D:/test/content.jasper","D:/test/"); } } //当文件是excel文件时 /*if(fileName.trim().toLowerCase().endsWith(".xls")||fileName.trim().toLowerCase().endsWith(".xlsx")) { System.out.println("是excel文件"+fileName); String excelFileName = new String("D:/test/"+fileName); int coloum = 0; // 比如你要获取第1列 try { HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFileName)); HSSFSheet sheet = workbook.getSheet("Sheet1");//创建一个Sheet1 //jdbc连接mysql * MySQL的JDBC URL编写方式:jdbc:mysql://主机名称:连接端口/数据库的名称?参数=值 * 避免中文乱码要指定useUnicode和characterEncoding * 执行数据库操作之前要在数据库管理系统上创建一个数据库,名字自己定, * 下面语句之前就要先创建javademo数据库 * Connection conn = null; String sql; String url = "jdbc:mysql://localhost:3306/test?user=root&password=zhxush&useUnicode=true&characterEncoding=UTF8"; // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来, // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来,下面三种形式都可以 Class.forName("com.mysql.jdbc.Driver");// 动态加载mysql驱动 // com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver(); // new com.mysql.jdbc.Driver(); System.out.println("成功加载MySQL驱动程序"); // 一个Connection代表一个数据库连接 conn = DriverManager.getConnection(url); // Statement里面带有很多方法,比如executeUpdate可以实现插入,更新和删除等 Statement stmt = conn.createStatement(); sql = "create table student(id char(100),name varchar(20),age varchar(20),sex varchar(20),primary key(id))"; int result = stmt.executeUpdate(sql);// executeUpdate语句会返回一个受影响的行数,如果返回-1就没有成功 System.out.println("创建数据表成 功"); for (int num = 0; num <= sheet.getLastRowNum(); num++) { HSSFRow row = sheet.getRow(num); if (null == row) { continue; } else { //if(row.getCell(coloum)!=null&&i==1){ OprationExcelVO oprationExcelVO = new OprationExcelVO(); //List<OprationExcelVO> listExcel = new ArrayList<OprationExcelVO>(); HSSFCell cell = row.getCell((int) coloum); row.getCell(coloum).setCellType(cell.CELL_TYPE_STRING); System.out.println("id="+row.getCell(coloum).getStringCellValue()); String id = row.getCell(coloum).getStringCellValue(); //cell.setCellValue("30"); //System.out.println(row.getCell(coloum).getStringCellValue()); coloum++; HSSFCell cell1 = row.getCell((int) coloum); row.getCell(coloum).setCellType(cell1.CELL_TYPE_STRING); System.out.println("name="+row.getCell(coloum).getStringCellValue()); String name = row.getCell(coloum).getStringCellValue(); coloum++; HSSFCell cell2 = row.getCell((int) coloum); row.getCell(coloum).setCellType(cell2.CELL_TYPE_STRING); System.out.println("age="+row.getCell(coloum).getStringCellValue()); String age = row.getCell(coloum).getStringCellValue(); coloum++; HSSFCell cell3 = row.getCell((int) coloum); row.getCell(coloum).setCellType(cell3.CELL_TYPE_STRING); System.out.println("sex="+row.getCell(coloum).getStringCellValue()); String sex = row.getCell(coloum).getStringCellValue(); //cell1.setCellValue("未知"); //System.out.println(row.getCell(coloum).getStringCellValue()); //} try { if (result != -1) { sql = "insert into student(id,name,age,sex) values('"+id+"','"+name+"','"+age+"','"+sex+"')"; result = stmt.executeUpdate(sql); sql = "insert into student(NO,name) values('2012002','周小俊')"; result = stmt.executeUpdate(sql); sql = "select * from student"; ResultSet rs = stmt.executeQuery(sql);// executeQuery会返回结果的集合,否则返回空值 System.out.println("id\t\t\t\t\t\t姓名\t\t年龄\t\t性别"); while (rs.next()) { System.out.println(rs.getString(1) + "\t" + rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4));// 入如果返回的是int类型可以用getInt() } } } catch (SQLException e) { System.out.println("MySQL操作错误"); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } coloum = 0; } } FileOutputStream out = null; try { out = new FileOutputStream(excelFileName); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); //conn.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }*/ } if (tempList[i].isDirectory()) { System.out.println("文件夹:"+tempList[i]); } // } catch (FileNotFoundException e) { // TODO Auto-generated catch block //e.printStackTrace(); }finally{ fis.close(); imageByteArray.clone(); } } outputStream.flush(); outputStream.close(); } public static void txtRead() throws IOException{ //OutputStream outputStream = new FileOutputStream("D:/test/photo.txt"); InputStream inputStream = new FileInputStream("D:/test/photo.txt"); byte[] imageByteArray = new byte[inputStream.available()]; inputStream.read(imageByteArray); BASE64Decoder decoder = new BASE64Decoder(); byte[] byteTxt = decoder.decodeBuffer(inputStream); OutputStream outputStream = new FileOutputStream("D:/test1/"); outputStream.write(byteTxt); outputStream.flush(); outputStream.close(); } //把xml获取出来的数据写入到PDF public static void xmlRead_writePdf(String xmlPath,String modelFile,String tempDir){ //System.out.println("xmlPath"+xmlPath); String strPath = new String("D:/test/"+xmlPath); List<OprationxmlVO> contentValueList = new ArrayList<OprationxmlVO>(); try{ //读取传入的路径,返回一个document对象 Document document = loadInit(strPath); //获取叶节点 NodeList contentNodeList = document.getElementsByTagName("content"); //遍历叶节点 short number = 0; Map<String, String> reportData = new HashMap<String, String>(); for(int i=0; i<contentNodeList.getLength(); i++){ /*获取xml所有的数据*/ String idNode = document.getElementsByTagName("ID").item(i).getFirstChild().getNodeValue(); String nameNode = document.getElementsByTagName("name").item(i).getFirstChild().getNodeValue(); String ageNode = document.getElementsByTagName("age").item(i).getFirstChild().getNodeValue(); String sexNode = document.getElementsByTagName("sex").item(i).getFirstChild().getNodeValue(); System.out.println("id="+idNode); System.out.println("name="+nameNode); System.out.println("age="+ageNode); System.out.println("sex="+sexNode); //把数据写入pdf File tempDirFile = new File(tempDir); if (!tempDirFile.exists()) { tempDirFile.mkdirs(); } //CreatePdfVO createPdfVO = new CreatePdfVO(); /*reportData.put("id", CreatePDF.isEmptyStr(createPdfVO.getName())?"":createPdfVO.getName()); reportData.put("name", CreatePDF.isEmptyStr(createPdfVO.getName())?"":createPdfVO.getName()); reportData.put("age", CreatePDF.isEmptyStr(createPdfVO.getName())?"":createPdfVO.getName()); reportData.put("sex", CreatePDF.isEmptyStr(createPdfVO.getName())?"":createPdfVO.getName());*/ reportData.put("id", idNode); reportData.put("name", nameNode); reportData.put("age", ageNode); reportData.put("sex", sexNode); //添加数据 //String pdfPath = tempDir +"content"+new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date()) + ".pdf"; String pdfPath = tempDir +"content.pdf"; boolean is; try { System.out.println("modelFile="+modelFile); System.out.println("pdfPath="+pdfPath); is= Report.createPDFReport(modelFile, pdfPath, reportData); System.out.println("生成PDF成功!"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("生成PDF异常!"); } } }catch(Exception e){ e.printStackTrace(); System.out.println(e.getMessage()); } } public static boolean isEmptyStr(Object str){ return str == null || str.toString().trim().length() < 1 ? true : false; } public static String objectToString(Object str){ if (null == str){ return null; }else{ return str.toString(); } } //把xml获取出来的数据写入到excel public static void xmlRead_writeExcel(String xmlPath)throws IOException{ //System.out.println("xmlPath"+xmlPath); String strPath = new String("D:/test/"+xmlPath); List<OprationxmlVO> contentValueList = new ArrayList<OprationxmlVO>(); try{ //读取传入的路径,返回一个document对象 Document document = loadInit(strPath); //获取叶节点 NodeList contentNodeList = document.getElementsByTagName("content"); //遍历叶节点 short number = 0; //InputStream isExcel = new FileInputStream(excelNamePath); // 创建Excel的工作书册 Workbook,对应到一个excel文档 HSSFWorkbook wb = new HSSFWorkbook(); // 创建Excel的工作sheet,对应到一个excel文档的tab HSSFSheet sheet = wb.createSheet("sheet1"); for(int i=0; i<contentNodeList.getLength(); i++){ /*获取xml所有的数据*/ String idNode = document.getElementsByTagName("ID").item(i).getFirstChild().getNodeValue(); String nameNode = document.getElementsByTagName("name").item(i).getFirstChild().getNodeValue(); String ageNode = document.getElementsByTagName("age").item(i).getFirstChild().getNodeValue(); String sexNade = document.getElementsByTagName("sex").item(i).getFirstChild().getNodeValue(); //把数据写入excel try { HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 HSSFCell cell=null; HSSFRow row1=null; String id = new String(UUID.randomUUID().toString()); row1 = sheet.createRow((short) number);//开始第几行输出 cell = row1.createCell((short) 0);//在第几行输出 cell.setCellStyle(style); cell.setCellValue(idNode); cell = row1.createCell((short) 1); cell.setCellStyle(style); cell.setCellValue(nameNode); cell = row1.createCell((short) 2); cell.setCellStyle(style); cell.setCellValue(ageNode); cell = row1.createCell((short) 3); cell.setCellStyle(style); cell.setCellValue(sexNade); number = (short) (number+1); FileOutputStream fout = new FileOutputStream("D:/test/operationExcel.xls"); wb.write(fout); System.out.println("文件已写入!"); fout.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block\ e.printStackTrace(); System.out.println("文件写入异常!"); } } }catch(Exception e){ e.printStackTrace(); System.out.println(e.getMessage()); } } public static Document loadInit(String filePath){ Document document = null; try{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.parse(new File(filePath)); document.normalize(); return document; }catch(Exception e){ e.printStackTrace(); System.out.println(e.getMessage()); return null; } } /*public static void main(String[] args) { getname("Demo.java"); getname("Demo1.java.txt"); } public static void getname(String filename) { //判断给定的文件名是否为空,并且长度要大于0 if ((filename!=null)&&(filename.length()>0)) { //查找字符‘.‘出现的最后一个索引位置 int x = filename.lastIndexOf("."); //判断此索引是否存在,并且不是最后一个字符 if ((x>-1)&&(x<filename.length()-1)) { System.out.println("已知程序的扩展名为:"+filename.substring(x+1)); //调用subString方法从索引位开始截取到最后,并且不截取字符'.' } } else { System.out.println("给定文件名错误"); } }*/ } ------------------------------------------------ package ThreadTime; import java.io.File; import java.util.HashMap; import java.util.Map; import com.tecsun.framework.unitl.Report; public class test{ public static void main(String[] args) { xmlRead_writePdf(); } public static void xmlRead_writePdf(){ Map<String, String> reportData = new HashMap<String, String>(); //把数据写入pdf reportData.put("id", "id"); reportData.put("name", "name"); reportData.put("age", "age"); reportData.put("sex", "sex"); boolean is; try { is= Report.createPDFReport("D:/test/content.jasper", "D:/content.pdf", reportData); System.out.println("生成PDF成功!"); } catch (Exception e) { e.printStackTrace(); System.out.println("生成PDF异常!"); } } } ============================================================== //请续看下一篇文章 ==============================================================