2019独角兽企业重金招聘Python工程师标准>>>

//定时器
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 RunnableTimer 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:00Timer 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 blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.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.txtif(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);//数据写入PDFSystem.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获取出来的数据写入到PDFpublic 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);//把数据写入pdfFile 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 blocke.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获取出来的数据写入到excelpublic 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();//把数据写入exceltry {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){   //判断给定的文件名是否为空,并且长度要大于0if ((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>();//把数据写入pdfreportData.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异常!");}}
} ==============================================================
//请续看下一篇文章
==============================================================

转载于:https://my.oschina.net/u/2336787/blog/392624

分享一个java对xml,excel,jdbc.properties,读写文件,读写图片等实现(1)相关推荐

  1. 分享一个JAVA专业接口开发利器,牛牛牛新鲜出炉!!!

    分享一个JAVA专业接口开发利器,集成在线接口文档 Swagger-ui,采用Jwt Token验证机制,最牛在于业务restful接口代码自动生成,更更牛的在接口可以做细化权限控制(例如:不同开发商 ...

  2. 分享一个java输出pdf的依赖包,非maven,包名:spire.pdf.jar 下载

    分享一个java输出pdf的依赖包,非maven,包名:spire.pdf.jar http://repo.e-iceblue.cn/#browse/browse:maven-public:e-ice ...

  3. 分享一个Java生成二维码工具类

    分享一个Java生成二维码工具类 直接上代码: 1.CodeUtil.class package top.lrshuai.blog.util;import java.awt.BasicStroke; ...

  4. 分享一个Java毕业设计项目——叮当书城项目

    拥有编程学习资源的UP,在此想为努力奋斗的计算机系的同学们助力,带来一个毕业设计思路. 下面的视频课程详细介绍了叮当书城项目部署,希望对大家有所帮助. ​项目文件代码介绍部分内容: 1.首先就是src ...

  5. 分享一个小工具:Excel表高速转换成JSON字符串

    在游戏项目中一般都须要由策划制作大量的游戏内容,当中非常大一部分是使用Excel表来制作的.于是程序就须要把Excel文件转换成程序方便读取的格式. 之前项目使用的Excel表导入工具都是通过Offi ...

  6. 分享一个java写的中国象棋代码以及相关视频

    注意:相关资料链接地址:http://pan.baidu.com/share/link?shareid=493847&uk=3223420628 若要详细视频请到该链接直接下载: http:/ ...

  7. 分享一个Java超市积分管理系统项目的制作方法。

    超市积分管理系统是典型的数据库信息管理系统,整个项目的设计.部署.实施具有信息管理系统的典型代表性,所以,作为毕业设计项目容易演示,并且便于将大学中所学到的知识融合进去,在模块设计.业务流程上都比较容 ...

  8. 记录一个java poi向excel插入图片的问题

    2019独角兽企业重金招聘Python工程师标准>>> public void addPictrue(String imgPath,HSSFSheet sheet, HSSFWork ...

  9. Java实现七牛云上传下载文件或图片

    文章目录 写在前面 一.准备工作 1.1.为什么选择七牛云? 1.2.七牛云注册 二.java操作七牛云对象存储下载 2.1.pom.xml引入依赖 2.2.上传下载具体代码 三.具体业务例子(七牛云 ...

最新文章

  1. 94年出生,如今985高校博士生导师!
  2. 代码大全读后感(二)
  3. 47. Permutations II 1
  4. 远程办公的一天:魔幻24小时
  5. web前端面试问答_Web服务面试问答
  6. 粉丝提问:有没有人会做彩虹表
  7. 用Visual C#来清空回收站(2)
  8. 最大子树和(洛谷-P1122)
  9. 自定义协同程序:CustomYieldInstruction
  10. 【luogu P2341 [HAOI2006]受欢迎的牛】 题解
  11. python 读取bin文件
  12. 大数据技术在物流中的应用
  13. 硬核科普 | 小谈 辣椒素和辣椒素受体 的研究,来自一线植物科研人员
  14. Android APK瘦身之Android Studio Lint (代码审查)
  15. 《Dynamically Fused Graph Network for Multi-hop Reasoning》 论文笔记
  16. java 集合元素自定义排序——Comparator.comparing , 不用实现 Comparable 接口
  17. 奶酪巫师的黑客乐园 - 第一个进行硬分叉的区块链游戏?
  18. git 分支教程小游戏
  19. 你是许三多还是成才?--《士兵突击》观后感
  20. [leetcode] online judge题目汇总

热门文章

  1. Spark Streaming中的操作函数分析
  2. 洛谷 P1049 装箱问题(01背包)
  3. 利用SparkSQL(java版)将离线数据或实时流数据写入hive的用法及坑点
  4. 【Linux 应用编程】进程管理 - 进程间通信IPC之共享内存 mmap
  5. PAT 1052. Linked List Sorting
  6. memcache windows64 位安装
  7. Java IO流总结(zz)
  8. mysql 添加int列_在MySQL中现有的int列的值中添加字符?
  9. detime php_php试题及答案
  10. gdi按钮重绘背景黑色_PS快速抠图换背景教程 PS怎么抠图放在另一张图 这个方法简单万能...