Java编程中常用工具函数
时间函数
日期字符串转换成Unix时间(ms)
// date to unix time
public static long getStringToDate(String mDateStr) {
long ret = -1;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
try {
date = formatter.parse(mDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ret = date.getTime();
return ret;
}
获取当前时间,按固定格式返回
public static String getNowTime() {
String ret = null;
long time = System.currentTimeMillis();
Date d1 = new Date(time);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ret = formatter.format(d1);
return ret;
}
unix时间(ms)转换为固定日期字符串
// unixtime to date
public static String getDateToString(long time) {
String ret = null;
Date d = new Date(time);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ret = formatter.format(time);
return ret;
}
日期的加减操作(加月份、或者加秒的操作类似):
// compute of time
public static void addDayOfDate(){
Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期
calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
System.out.println(calendar.get(Calendar.DATE));//加1之后的日期Top
}
文件函数
从文件中读取内容:
public static void readToBuffer(StringBuffer buffer, String filePath) throws IOException {
InputStream is = new FileInputStream(filePath);
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
line = reader.readLine();
while (line != null) {
buffer.append(line);
buffer.append("\n");
line = reader.readLine();
}
reader.close();
is.close();
}
public static String readFile(String filePath) throws IOException {
StringBuffer sb = new StringBuffer();
FileUtils.readToBuffer(sb, filePath);
return sb.toString();
}
字符串写入函数
public class WriteFileExample {
public static void main(String[] args) {
FileOutputStream fop = null;
File file;
String content = "This is the text content";
try {
file = new File("c:/newfile.txt");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}