收集于网络
标签: 时间,时间工具,时间工具类
``
/**
-
时间工具类
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = “yyyy”;public static String YYYY_MM = “yyyy-MM”;
public static final String YYYY_MM_DD = “yyyy-MM-dd”;
public static final String YYYYMMDDHHMMSS = “yyyyMMddHHmmss”;
public static final String YYYY_MM_DD_HH_MM_SS = “yyyy-MM-dd HH:mm:ss”;
private static final String[] parsePatterns = {
“yyyy-MM-dd”, “yyyy-MM-dd HH:mm:ss”, “yyyy-MM-dd HH:mm”, “yyyy-MM”,
“yyyy/MM/dd”, “yyyy/MM/dd HH:mm:ss”, “yyyy/MM/dd HH:mm”, “yyyy/MM”,
“yyyy.MM.dd”, “yyyy.MM.dd HH:mm:ss”, “yyyy.MM.dd HH:mm”, “yyyy.MM”};/**
- 获取当前Date型日期
- @return Date() 当前日期
*/
public static Date getNowDate() {
return new Date();
}
/**
- 获取当前日期, 默认格式为yyyy-MM-dd
- @return 日期格式化字符串
*/
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}public static String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}public static String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}public static String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}public static String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}/**
- 日期路径 即年/月/日 如2018/08/08
*/
public static String datePath() {
Date now = new Date();
return DateFormatUtils.format(now, “yyyy/MM/dd”);
}
/**
- 日期路径 即年/月/日 如20180808
*/
public static String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, “yyyyMMdd”);
}
/**
- 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
- 获取服务器启动时间
*/
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
/**
- 计算两个时间差
*/
public static String getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
// long ns = 1000;
// 获得两个时间的毫秒时间差异
long diff = endDate.getTime() - nowDate.getTime();
// 计算差多少天
long day = diff / nd;
// 计算差多少小时
long hour = diff % nd / nh;
// 计算差多少分钟
long min = diff % nd % nh / nm;
// 计算差多少秒//输出结果
// long sec = diff % nd % nh % nm / ns;
return day + “天” + hour + “小时” + min + “分钟”;
}
}
``
标签: 获取网络请求地址ip,计算机名
/**
* 获取请求 IP (WEB 服务)
*
* @return IP 地址
*/
public static String getIpAddr() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if (ip.equals("127.0.0.1")) {
//根据网卡取本机配置的 IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ip = inet.getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 多个代理的情况,第一个 IP 为客户端真实 IP,多个 IP 按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 0) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
/**
* 获取当前计算机 IP
*/
public static String getHostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "127.0.0.1";
}
/**
* 获取当前计算机名称
*/
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "未知";
}
标签: web请求,request,response, Json
public class WebHelper {
/**
* 是否是Ajax请求
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String requestedWith = request.getHeader("x-requested-with");
return "XMLHttpRequest".equalsIgnoreCase(requestedWith);
}
/**
* 输出JSON
*/
public static void writeJson(Object object, ServletResponse response) {
PrintWriter out = null;
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
out = response.getWriter();
out.write(JSONUtil.toJsonStr(object));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
public static void redirectUrl(String redirectUrl) {
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
try {
response.sendRedirect(redirectUrl);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取当前请求的 Http Method
* @return
*/
public static String getRequestHTTPMethod() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request.getMethod();
}
}
标签: 服务器, 服务器相关信息
/**
-
服务器相关信息
*/
public class Server {private static final int OSHI_WAIT_SECOND = 1000;
/**
- CPU相关信息
*/
private Cpu cpu = new Cpu();
/**
- 內存相关信息
*/
private Mem mem = new Mem();
/**
- JVM相关信息
*/
private Jvm jvm = new Jvm();
/**
- 服务器相关信息
*/
private Sys sys = new Sys();
/**
- 磁盘相关信息
*/
private List sysFiles = new LinkedList<>();
public Cpu getCpu() {
return cpu;
}public void setCpu(Cpu cpu) {
this.cpu = cpu;
}public Mem getMem() {
return mem;
}public void setMem(Mem mem) {
this.mem = mem;
}public Jvm getJvm() {
return jvm;
}public void setJvm(Jvm jvm) {
this.jvm = jvm;
}public Sys getSys() {
return sys;
}public void setSys(Sys sys) {
this.sys = sys;
}public List getSysFiles() {
return sysFiles;
}public void setSysFiles(List sysFiles) {
this.sysFiles = sysFiles;
}public void copyTo() throws Exception {
SystemInfo si = new SystemInfo();
HardwareAbstractionLayer hal = si.getHardware();setCpuInfo(hal.getProcessor()); setMemInfo(hal.getMemory()); setSysInfo(); setJvmInfo(); setSysFiles(si.getOperatingSystem());
}
/**
- 设置CPU信息
*/
private void setCpuInfo(CentralProcessor processor) {
// CPU信息
long[] prevTicks = processor.getSystemCpuLoadTicks();
Util.sleep(OSHI_WAIT_SECOND);
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
cpu.setCpuNum(processor.getLogicalProcessorCount());
cpu.setTotal(totalCpu);
cpu.setSys(cSys);
cpu.setUsed(user);
cpu.setWait(iowait);
cpu.setFree(idle);
}
/**
- 设置内存信息
*/
private void setMemInfo(GlobalMemory memory) {
mem.setTotal(memory.getTotal());
mem.setUsed(memory.getTotal() - memory.getAvailable());
mem.setFree(memory.getAvailable());
}
/**
- 设置服务器信息
*/
private void setSysInfo() {
Properties props = System.getProperties();
sys.setComputerName(IPUtils.getHostName());
sys.setComputerIp(IPUtils.getHostIp());
sys.setOsName(props.getProperty(“os.name”));
sys.setOsArch(props.getProperty(“os.arch”));
sys.setUserDir(props.getProperty(“user.dir”));
}
/**
- 设置Java虚拟机
*/
private void setJvmInfo() {
Properties props = System.getProperties();
jvm.setTotal(Runtime.getRuntime().totalMemory());
jvm.setMax(Runtime.getRuntime().maxMemory());
jvm.setFree(Runtime.getRuntime().freeMemory());
jvm.setVersion(props.getProperty(“java.version”));
jvm.setHome(props.getProperty(“java.home”));
}
/**
- 设置磁盘信息
*/
private void setSysFiles(OperatingSystem os) {
FileSystem fileSystem = os.getFileSystem();
OSFileStore[] fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray) {
long free = fs.getUsableSpace();
long total = fs.getTotalSpace();
long used = total - free;
SysFile sysFile = new SysFile();
sysFile.setDirName(fs.getMount());
sysFile.setSysTypeName(fs.getType());
sysFile.setTypeName(fs.getName());
sysFile.setTotal(convertFileSize(total));
sysFile.setFree(convertFileSize(free));
sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(Arith.mul(Arith.div(used, total, 4), 100));
sysFiles.add(sysFile);
}
}
/**
- 字节转换
- @param size 字节大小
- @return 转换后值
*/
public String convertFileSize(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? “%.0f MB” : “%.1f MB”, f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? “%.0f KB” : “%.1f KB”, f);
} else {
return String.format("%d B", size);
}
}
- CPU相关信息
标签:文件,文件夹,文件下载
@RestController
public class FileController {
@Autowired
FileService fileService;
// 通过路径来存储文件
@RequestMapping(value = "/exclude/file/upload/byPath.json", method = RequestMethod.POST)
public Response uploadThisFileByPath(String filePath, HttpServletRequest request) {
Response response = new Response();
File sourcefile = new File(filePath);
if(!sourcefile.exists()){
return response.failure("文件不存在,请重试");
}
String filename = sourcefile.getName();//获取文件名称
String suffixname = filename.substring(filename.lastIndexOf("."));//后缀
String projectPath = fileService.getProjectPath(request);
String timePath = fileService.getTimePath();
String uuid = CommonUtil.getUUID();
String destfilePath = projectPath + File.separator + "myProjectPhotos" + File.separator + timePath + File.separator;
File dest = fileService.createFileUsePath(destfilePath, uuid + suffixname);
try {
//拷贝文件到指定路径储存,MultipartFile对象的transferTo方法用于文件的保存(效率和操作比原来用的FileOutputStream方便和高效)
FileUtil.copyFile(filePath, dest.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
return response.failure("上传失败... 请重试");
}
Map resMap = new HashMap();
resMap.put("photo_name", filename);
resMap.put("photo_url", dest.getAbsolutePath().replaceAll("\\\\", "/"));
return response.success(resMap);
}
@RequestMapping(value = "/exclude/file/upload.json", method = RequestMethod.POST)
public Response uploadThisFile(@RequestParam(value = "myFile") MultipartFile file, HttpServletRequest request) throws IOException {
String filename = file.getOriginalFilename();//获取文件名称
String suffixname = filename.substring(filename.lastIndexOf("."));//后缀
String projectPath = fileService.getProjectPath(request);
String timePath = fileService.getTimePath();
String uuid = CommonUtil.getUUID();
String filePath = projectPath + File.separator + "myProjectPhotos" + File.separator + timePath + File.separator;
File dest = fileService.createFileUsePath(filePath, uuid + suffixname);
Response response = new Response();
try {
//拷贝文件到指定路径储存,MultipartFile对象的transferTo方法用于文件的保存(效率和操作比原来用的FileOutputStream方便和高效)
file.transferTo(dest);
// FileInputStream fileInputStream = new FileInputStream(dest);
// ileService.saveDataToMysql(fileInputStream);
} catch (Exception e) {
e.printStackTrace();
return response.failure(“上传失败… 请重试”);
}
Map resMap = new HashMap();
resMap.put(“photo_name”, filename);
resMap.put(“photo_url”, dest.getAbsolutePath().replaceAll("\\", “/”));
return response.success(resMap);
}
@RequestMapping(value = "/exclude/file/delete.json", method = RequestMethod.POST)
public Response deleteThisFile(String path) {
Response response = new Response();
try {
File myDelFile = new File(path);
myDelFile.delete();
} catch (Exception e) {
e.printStackTrace();
return response.failure("删除文件操作出错");
}
return response.success("删除成功");
}
}
@Service
public class FileService {
public String getProjectPath(HttpServletRequest request){
return request.getServletContext().getRealPath("/");
}
// 创建文件
public File createFileUsePath(String path, String fileName){
File destPath = new File(path);
File dest = new File(path + File.separator + fileName);
if (!dest.exists()) {
try {
destPath.mkdirs();
dest.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return dest;
}
public String getTimePath(){
Calendar now = Calendar.getInstance();
String years = "" + now.get(Calendar.YEAR) ;
String months = (now.get(Calendar.MONTH) + 1) < 10? "0"+(now.get(Calendar.MONTH) + 1): "" + (now.get(Calendar.MONTH) + 1);
String days = now.get(Calendar.DAY_OF_MONTH) < 10?"0"+now.get(Calendar.DAY_OF_MONTH): "" +now.get(Calendar.DAY_OF_MONTH) ;
return years + months + days ;
}
public void saveDataToMysql(FileInputStream file){
try{
// FileInputStream file = new FileInputStream("C:\\shanshui.jpg");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(Constants.Jdbc_Url, Constants.Jdbc_Username, Constants.Jdbc_Password);
PreparedStatement ps = conn.prepareStatement("insert into my_yh values(?,?,?)");
ps.setInt(1,23);
ps.setString(2,"zhangsan");
ps.setBinaryStream(3, file, file.available());
ps.executeUpdate();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
标签: 流, 转换,解析json,输入流, 输出流,文件
读取文件为输入流
InputStream fileInputStream = new FileInputStream(“D:\qqq.txt”);
String streamToStr = getStreamToStr(fileInputStream);
输入流转换为字符串
``public static String getStreamToStr(InputStream tInputStream) {
if (tInputStream != null) {
try {
BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream));
StringBuffer tStringBuffer = new StringBuffer();
String sTempOneLine;
while ((sTempOneLine = tBufferedReader.readLine()) != null) {
tStringBuffer.append(sTempOneLine);
}
return tStringBuffer.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
网络请求获取数据,再用fastjson解析
private void getUrl(){
//
String url = "http:xxfdddddddddd=" ;
String resBody = "";
try {
resBody = HttpServer.doGet(url);
com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(resBody);
com.alibaba.fastjson.JSONArray data = jsonObject.getJSONArray("data");
List<String> retList = JSON.parseObject(String.valueOf(data), List.class);
} catch (Exception e) {
}
}
``