一个定时生成文件的java小程序
本文最后更新于 2016 天前,其中的信息可能已经有所发展或是发生改变。

今晚学习了java->Timer 类的使用

然后回想了之前是用java->Quartz 定时执行,然后今天写了一个小程序是用Timer类,感觉还行,这个小程序我也可以后期做第二次开发嘻嘻

记录一下。


小程序就几个类而已;

pox.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.glj</groupId>
	<artifactId>hdpShare</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>iot-share</name>
	<url>http://maven.apache.org</url>
	
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.7</java.version>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.3.0</version>
		</dependency>
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>5.1.38</version>
		</dependency>
	</dependencies>
	<build>
	  	<finalName>hdpShare</finalName>
	  	<pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.eclipse.m2e</groupId>
                    <artifactId>lifecycle-mapping</artifactId>
                    <version>1.0.0</version>
                    <configuration>
                        <lifecycleMappingMetadata>
                            <pluginExecutions>
                                <pluginExecution>
                                    <pluginExecutionFilter>
                                        <groupId>org.apache.maven.plugins</groupId>
                                        <artifactId>maven-dependency-plugin</artifactId>
                                        <versionRange>[2.0,)</versionRange>
                                        <goals>
                                            <goal>copy-dependencies</goal>
                                        </goals>
                                    </pluginExecutionFilter>
                                    <action>
                                        <ignore />
                                    </action>
                                </pluginExecution>
                            </pluginExecutions>
                        </lifecycleMappingMetadata>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
	  	<plugins>
	  		<plugin>
	  			<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>  
				<version>3.2</version>
				<configuration>  
	            	<source>${java.version}</source>
					<target>${java.version}</target>
					<encoding>${project.build.sourceEncoding}</encoding>
	            </configuration> 
	  		</plugin>
	  		<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<includeScope>compile</includeScope>
							<excludeScope>test</excludeScope>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<overWriteReleases>false</overWriteReleases>
							<overWriteSnapshots>false</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
						</configuration>
					</execution>
				</executions>
			</plugin>
	  	</plugins>
	  </build>
</project>

FileWriter(文件写入)

package com.glj.main;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.glj.service.ShareService;
import com.glj.util.ConfigUtil;

public class FileWriter {
	private static final Logger log = Logger.getLogger(FileWriter.class);
	private static final String ENCODING = "utf-8";
	private String statDate;
	private String path;
	
	public FileWriter() {}
	
	public FileWriter(String statDate,String path) {
		this.path = path;
		this.statDate = statDate;
	}
	
	public void write() {
		ShareService service = new ShareService(statDate);
		List<Map<String,Object>> dataList = service.getShareDate();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < dataList.size(); i++) {
			sb.append(dataList.get(i).get("imei")+",");
			sb.append(dataList.get(i).get("apn")).append(System.lineSeparator());
		}
		
		try {
			File file = new File(path);
			FileUtils.writeStringToFile(file, sb.toString(), ENCODING, false);
			log.info("写入数据完成!"+path);
		} catch (IOException e) {
			log.error("写入数据文件出错:"+path, e);
		}
	}
	public static void main(String[] args) {
		String statDate = "2018-01-30";
		String path = ConfigUtil.getProperty("share.path")+File.separator+statDate+".txt";
		FileWriter fw = new FileWriter(statDate, path);
		fw.write();
	}
	
}

MainSchedule定时跑的类

package com.glj.main;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.glj.util.ConfigUtil;

public class MainSchedule {
	private static Logger log = Logger.getLogger(MainSchedule.class);
	
	public static void main(String[] args) {
		int startTime = Integer.parseInt(ConfigUtil.getProperty("share.statTime"));
		int startMin = Integer.parseInt(ConfigUtil.getProperty("share.statMin"));
		System.out.println("第一次开始时间:"+startTime+":"+startMin);
		
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, 0); // 第二天开始执行
		calendar.set(Calendar.HOUR_OF_DAY, startTime); 
		calendar.set(Calendar.MINUTE, startMin);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
			@Override
			public void run() {
				SimpleDateFormat dateFromat = new SimpleDateFormat("yyyy-MM-dd");
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DATE, -1);
				
				String statDate = dateFromat.format(calendar.getTime());
				String path = ConfigUtil.getProperty("share.path")+File.separator+statDate+".txt";
				System.out.println(statDate);
				System.out.println(path);
				log.info("开始生成文件");
				FileWriter fw = new FileWriter(statDate, path);
				fw.write();
			}
		};
		timer.scheduleAtFixedRate(timerTask, calendar.getTime(),24 * 60 * 60 * 1000);
	}
}

ShareService

package com.glj.service;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.glj.util.JDBCUtil;

public class ShareService {
	private static final Logger log = Logger.getLogger(ShareService.class);
	private String statDate = "";
	
	public ShareService() {
	}
	/**
	 * 日期格式YYYY-MM-DD
	 * @param statDate
	 */
	public ShareService(String statDate) {
		this.statDate = statDate;
	}
	
	public List<Map<String,Object>> getShareDate() {
		String sql = "select imei,apn from wajuepingfen_apn where lt ='"+statDate+"' ";
		List<Map<String,Object>>  list = JDBCUtil.executeSQLWithResultList(sql);
		return list;
	}
	
}

ConfigUtil(工具类)

package com.glj.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class ConfigUtil {
	private static final Logger log = Logger.getLogger(ConfigUtil.class);
	private static Properties prop = null;
	
	public ConfigUtil(InputStream is) {
		prop = new Properties();

        try(BufferedInputStream bis = new BufferedInputStream(is);
        	InputStream in = bis){
        	prop.load(in);
        }catch (Exception e){
        	log.error("读取"+prop+"配置文件错误!", e);
        }
    }
	
	public static void init(String cfgPath) {
		String realPath = "";
		if(StringUtils.isNotBlank(cfgPath) && new File(cfgPath).exists()) {
			realPath = cfgPath;
		}else {
			//优先读取上一级目录中的cfg,如果不存在,再读取bin目录中的cfg
//			String defPath = "../cfg.properties";
			String defPath = "../cfg.properties";
			String defExistsPath = ClassLoader.getSystemResource("").getPath()+File.separator+"cfg.properties";
			realPath = new File(defPath).exists()? defPath: defExistsPath;
		}
		System.out.println(realPath);
		try{
			InputStream is = StringUtils.isNotBlank(realPath)? new FileInputStream(realPath): 
				ConfigUtil.class.getResourceAsStream("/cfg.properties");
			log.info("读取配置文件:"+realPath);
			new ConfigUtil(is);
		} catch (IOException e1) {
			log.error("读取配置文件出错");
		}
	}
	
	public static String getProperty(String propertyName) {
		if(prop == null) {
			ConfigUtil.init("");
		}
		if("".equals(propertyName) || null==propertyName) {
			return "";
		}
		return prop.getProperty(propertyName);
	}
	public static void main(String[] args) {
		System.out.println(ConfigUtil.getProperty("mysql.url"));
	}
}

JDBCUtil(数据库链接工具类)

package com.glj.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class JDBCUtil {
	private static final Logger log = Logger.getLogger(JDBCUtil.class);
	
	public static Connection getDefaultConn() throws Exception {
		String mysqlUrl = ConfigUtil.getProperty("mysql.url");
		String mysqlUserName = ConfigUtil.getProperty("mysql.userName");
		String mysqlPassWord = ConfigUtil.getProperty("mysql.password");
		return getConn(mysqlUrl, mysqlUserName, mysqlPassWord);
	}
	
	public static Connection getConn(String url, String username, String password) throws Exception{
		String driverName = ConfigUtil.getProperty("mysql.className");
		Connection conn = null;
		try{
			Class.forName(driverName);
			conn = DriverManager.getConnection(url,username,password);
		}catch (ClassNotFoundException e){
			log.error("数据库驱动文件不存在");
			throw e;
		}catch (SQLException e) {
			log.error("获取数据库连接失败");
			throw e;
		}
		return conn;
	}
	public static void insertOrUpdateSQL(String sql) {
		Connection conn = null;
		Statement stat = null;
		try {
			conn = getDefaultConn();
			conn.setAutoCommit(false);
			stat = conn.createStatement();
			stat.executeUpdate(sql);
			conn.commit();
		} catch (Exception e) {
			log.error("insertOrUpdateSQL出错:--->"+e);
		}finally{
			close(conn, stat);
		}
		
	}
	public static List<Map<String,Object>> executeSQLWithResultList(String sql) {
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		Map<String,Object> map = null;
		
		try {
			conn = getDefaultConn();
			stat = conn.createStatement();
			rs = stat.executeQuery(sql);
			while(rs.next()){
				map = new HashMap<String,Object>();
				int colCounts = rs.getMetaData().getColumnCount();
				for(int i=1; i<=colCounts;i++){
					map.put(rs.getMetaData().getColumnName(i).toLowerCase(), rs.getObject(i));
				}
				list.add(map);
			}
		} catch (SQLException e) {
			log.error("查询出错"+e);
		} catch (Exception e) {
			log.error("数据链接错误"+e);
		}finally{
			close(conn, stat, rs);
		}
		return list;
	}
	public static void close(Connection conn, Statement stat) {
		try {
			if (stat != null) stat.close();
			if (conn != null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void close(Connection conn, Statement stat, ResultSet rs) {
		try {
			if (rs != null) rs.close();
			if (stat != null) stat.close();
			if (conn != null) conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
}

cfg.properties配置文件

#mysql
mysql.className=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/work?characterEncoding=UTF-8
mysql.userName=root
mysql.password=root

#share.path=/home/iotshare/shareFiles
share.path=G:\pushFile_test
share.statTime=23
share.statMin=54

log4j.properties配置文件

log4j.rootLogger=stdout,ERROR,logfile
#\u8f93\u51fa\u5230\u63a7\u5236\u53f0#  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=INFO
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d %-5p [%-8t] [%-17c{1}]-%m%n

#\u8f93\u51fa\u5230\u9879\u76ee\u6587\u4ef6\u4e0b#
log4j.appender.logfile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File = ./logs/info_log.log
log4j.appender.logfile.Append = true
log4j.appender.logfile.Threshold = INFO
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n
##log4j.appender.logfile.layout.ConversionPattern= %d %-5p [%-8t] [%-17c{1}]-%m%n

#\u9519\u8bef\u4fe1\u606f\u8f93\u51fa\u5230\u9879\u76ee\u5b50\u6587\u4ef6\u5939\u4e0b#
log4j.appender.ERROR=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERROR.File = ./logs/err_log.log
log4j.appenile.ERROR.Append = true
log4j.appender.ERROR.Threshold = ERROR
log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.ERROR.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss,SSS} %5p %c{1}:%L - %m%n

生成文件成功…

好了,应该能让我再优化以后公司需求对外也能做二次开发使用吧…

记录完成睡觉…


暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇