public class IpUtils{ private static Map<String, Object> map = SingletonMap.getInstance(); /** * blob轉byte array * @param blob * @return * @throws SQLException */ public static byte[] blob2ByteArr(Blob blob) throws SQLException { if (blob == null) { return null; } BufferedInputStream is = null; try { is = new BufferedInputStream(blob.getBinaryStream()); byte[] bytes = new byte[(int) blob.length()]; int len = bytes.length; int offset = 0; int read = 0; while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) { offset += read; } return new String(bytes,"GBK").getBytes(); } catch (Exception e) { return null; } finally { try { is.close(); is = null; } catch (IOException e) { return null; } } } /** * 獲取ip地址 * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip != null && !ip.isEmpty()) { ip = ip.split(",")[0].trim(); } 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(); } return ip; } /** * 獲取當前月份 * @return */ public static int getMonth() { Calendar c = Calendar.getInstance(); return c.get(Calendar.MONTH) + 1; } /** * 獲取當前月份 * @return */ public static int getDay() { Calendar c = Calendar.getInstance(); return c.get(Calendar.DAY_OF_MONTH); } /** * 得到當前classpath路徑 * @author ming * */ public static String getClasspath (String path) { if (path == null) { path = ""; } String classpath = Thread.currentThread().getContextClassLoader().getResource(path).getPath(); return classpath; } /** * @author ming * 得到默認路徑 */ public static String getDefaultClasspath () { return getClasspath(null); } /** * 得到webinfo路徑 * @author ming */ public static String getWebInfPath () { String classpath = getClasspath(null); return classpath.replace("classes/", ""); } /** * @author ming * 得到項目根目錄路徑 */ public static String getRootPath () { return (String)map.get(Constant.ROOT_PATH_KEY); } /** * 保存文件到指定路徑 * @param stream * @param path * @param filename * @return * @throws IOException */ @SuppressWarnings("unused") public static File saveFileFromInputStream(InputStream stream, String path, String filename) throws IOException { File file = new File(path + File.separator + filename); FileOutputStream fs = new FileOutputStream(file); byte[] buffer = new byte[1024 * 1024]; int bytesum = 0; int byteread = 0; while ((byteread = stream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); fs.flush(); } fs.close(); stream.close(); return file; } }
根據ip獲取地理位置/天氣信息等:java