总结一
1、提取HTML标签的属性值
public List<String> match(String source, String element, String attr) {
List<String> result = new ArrayList<String>();
String reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?\\s.*?>";
Pattern pt = Pattern.compile(reg);
Matcher m = pt.matcher(source);
while (m.find()) {
String r = m.group(1);
result.add(r);
}
return result;
}
2、JPA下执行原生SQL
protected List<Map<String, Object>> handleNativeSql(String sql, String[] columns) {
List<Map<String, Object>> list = handleSql(sql, null, columns);
return list;
}
private List<Map<String, Object>> handleSql(String sql, PageRequest pageRequest, String[] columns) {
Query query = entityManager.createNativeQuery(sql);
if (pageRequest != null) {
query.setFirstResult(pageRequest.getPageNumber() * pageRequest.getPageSize());
query.setMaxResults(pageRequest.getPageSize());
}
List<Object[]> list = query.getResultList();
List<Map<String, Object>> list_ = new ArrayList<>();
Map<String, Object> map = null;
String key = "0";
for (Object[] arrs : list) {
map = new HashMap<String, Object>();
for (int i = 0; i < arrs.length; i++) {
key = columns == null ? i + "" : columns[i];
map.put(key, arrs[i]);
}
list_.add(map);
}
return list_;
}
3、文件拷贝
public static void copyNioTransfer(String sourcePath, String targetPath, String fileName) {
File source = new File(sourcePath);
File targetDir = new File(targetPath);
if (!targetDir.exists())
targetDir.mkdirs();
File target = new File(targetPath + "/" + fileName);
FileChannel in = null;
FileChannel out = null;
FileInputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
in = inStream.getChannel();
out = outStream.getChannel();
in.transferTo(0L, in.size(), out);
} catch (IOException e) {
e.printStackTrace();
try {
inStream.close();
in.close();
outStream.close();
out.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
} finally {
try {
inStream.close();
in.close();
outStream.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4、文件数据操作
public static void delFile(String filePath) {
File f = new File(filePath);
f.delete();
}
public static void delSuffixFile(String filePath, String suffix) {
File dir = new File(filePath);
File[] fs = dir.listFiles();
for (File f : fs) {
if (!f.getName().endsWith(suffix))
continue;
f.delete();
}
}
public static String fileName(String filePath) {
File f = new File(filePath);
return f.getName();
}
public static String dirpath(String filePath) {
File f = new File(filePath);
String path = "";
if (f.isFile())
path = filePath.substring(0, filePath.indexOf(f.getName()));
return path;
}
public static void delDir(String filePath) {
if (!filePath.endsWith(File.separator))
filePath = filePath + File.separator;
File dirFile = new File(filePath);
if ((!dirFile.exists()) || (!dirFile.isDirectory()))
return;
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++)
if (files[i].isFile())
delFile(files[i].getAbsolutePath());
else
delDir(files[i].getAbsolutePath());
dirFile.delete();
}
public static boolean renameFile(String resFilePath, String newFileName) {
File f = new File(resFilePath);
String newFilePath = f.getParent() + File.separator + newFileName;
File resFile = new File(resFilePath);
File newFile = new File(newFilePath);
return resFile.renameTo(newFile);
}
5、读文件的内容
public static String readFileContent(String filePath) throws IOException {
return readFileContent(filePath, null, null, 1024);
}
public static String readFileContent(String filePath, String encoding) throws IOException {
return readFileContent(filePath, encoding, null, 1024);
}
public static String readFileContent(String filePath, int bufLen) throws IOException {
return readFileContent(filePath, null, null, bufLen);
}
public static String readFileContent(String filePath, String encoding, String sep) throws IOException {
return readFileContent(filePath, encoding, sep, 1024);
}
public static String readFileContent(String filePath, String encoding, String sep, int bufLen) throws IOException {
if ((filePath == null) || (filePath.equals("")))
return "";
if ((sep == null) || (sep.equals("")))
sep = "\n";
if (!new File(filePath).exists())
return "";
StringBuffer str = new StringBuffer("");
FileInputStream fs = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fs = new FileInputStream(filePath);
if ((encoding == null) || (encoding.trim().equals("")))
isr = new InputStreamReader(fs);
else
isr = new InputStreamReader(fs, encoding.trim());
br = new BufferedReader(isr, bufLen);
String data = "";
while ((data = br.readLine()) != null)
str.append(data).append(sep);
} catch (IOException e) {
throw e;
} finally {
try {
if (br != null)
br.close();
if (isr != null)
isr.close();
if (fs != null)
fs.close();
} catch (IOException e) {
throw e;
}
}
return str.toString();
}
6、向文件中写入内容
public static boolean newFile(String path, String fileName, StringBuffer content) throws IOException {
return newFile(path, fileName, content, 1024, false);
}
public static boolean newFile(String path, String fileName, StringBuffer content, boolean isWrite)
throws IOException {
return newFile(path, fileName, content, 1024, isWrite);
}
public static boolean newFile(String path, String fileName, StringBuffer content, int bufLen, boolean isWrite)
throws IOException {
if ((path == null) || (path.equals("")) || (content == null) || (content.equals("")))
return false;
boolean flag = false;
FileWriter fw = null;
BufferedWriter bw = null;
File file = new File(path);
if (!file.exists())
file.mkdirs();
try {
fw = new FileWriter(path + File.separator + fileName, isWrite);
bw = new BufferedWriter(fw, bufLen);
bw.write(content.toString());
flag = true;
} catch (IOException e) {
System.out.println("写入文件出错");
flag = false;
throw e;
} finally {
if (bw != null) {
bw.flush();
bw.close();
}
if (fw != null)
fw.close();
}
return flag;
}
public static boolean newFile(String path, String fileName, String content) throws IOException {
return newFile(path, fileName, content, 1024, false);
}
public static boolean newFile(String path, String fileName, String content, boolean isWrite) throws IOException {
return newFile(path, fileName, content, 1024, isWrite);
}
public static boolean newFile(String path, String fileName, String content, int bufLen, boolean isWrite)
throws IOException {
if ((path == null) || (path.equals("")) || (content == null) || (content.equals("")))
return false;
boolean flag = false;
FileWriter fw = null;
BufferedWriter bw = null;
File file = new File(path);
if (!file.exists())
file.mkdirs();
try {
fw = new FileWriter(path + File.separator + fileName, isWrite);
bw = new BufferedWriter(fw, bufLen);
bw.write(content);
flag = true;
} catch (IOException e) {
System.out.println("写入文件出错");
flag = false;
throw e;
} finally {
if (bw != null) {
bw.flush();
bw.close();
}
if (fw != null)
fw.close();
}
return flag;
}
public static boolean newFolder(String filePath) throws Exception {
boolean flag = false;
if ((filePath == null) || (filePath.equals("")) || (filePath.equals("null")))
return flag;
try {
File myFilePath = new File(filePath);
if (!myFilePath.exists())
myFilePath.mkdirs();
flag = true;
} catch (Exception e) {
throw e;
}
return flag;
}
public static boolean copyFile(String sourcePath, String targetPath) throws IOException {
return copyFile(sourcePath, targetPath, null);
}
public static boolean copyFile(String oldPath, String newPath, String newFileName) throws IOException {
boolean flag = false;
if ((oldPath == null) || (newPath == null) || (newPath.equals("")) || (oldPath.equals("")))
return flag;
InputStream inStream = null;
FileOutputStream fs = null;
try {
int bytesum = 0;
int byteread = 0;
File file = null;
file = new File(newPath);
if (!file.exists())
file.mkdirs();
file = new File(oldPath);
if (file.exists()) {
inStream = new FileInputStream(oldPath);
if ((newFileName == null) || (newFileName.equals("")))
newFileName = file.getName();
fs = new FileOutputStream(newPath + File.separator + newFileName);
byte[] buffer = new byte[8192];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
flag = true;
}
} catch (IOException e) {
throw e;
} finally {
try {
if (fs != null)
fs.close();
if (inStream != null)
inStream.close();
} catch (IOException e) {
throw e;
}
}
return flag;
}
public static void copyFolder(String oldPath, String newPath) throws Exception {
if ((oldPath == null) || (newPath == null) || (newPath.equals("")) || (oldPath.equals("")))
return;
FileInputStream input = null;
FileOutputStream output = null;
try {
File temp = null;
temp = new File(newPath);
if (!temp.exists())
temp.mkdirs();
temp = new File(oldPath);
String[] file = temp.list();
for (int i = 0; i < file.length; i++) {
if (oldPath.endsWith(File.separator))
temp = new File(oldPath + file[i]);
else
temp = new File(oldPath + File.separator + file[i]);
if (temp.isFile()) {
input = new FileInputStream(temp);
output = new FileOutputStream(newPath + File.separator + temp.getName().toString());
byte[] b = new byte[8192];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
}
if (!temp.isDirectory())
continue;
copyFolder(oldPath + File.separator + file[i], newPath + File.separator + file[i]);
}
} catch (Exception e) {
throw e;
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (Exception e) {
throw e;
}
}
}
public static boolean Move(String srcFile, String destPath) {
return Move(srcFile, destPath, null);
}
public static boolean Move(String srcFile, String destPath, String newFileName) {
boolean flag = false;
if ((srcFile == null) || (srcFile.equals("")) || (destPath == null) || (destPath.equals("")))
return flag;
File file = new File(srcFile);
File dir = new File(destPath);
if ((newFileName == null) || (newFileName.equals("")) || (newFileName.equals("null")))
newFileName = file.getName();
flag = file.renameTo(new File(dir, newFileName));
return flag;
}
public static void moveFile(String oldPath, String newPath) throws Exception {
if (copyFile(oldPath, newPath))
delFile(oldPath);
}
public static void moveFile(String oldPath, String newPath, String newFileName) throws Exception {
if (copyFile(oldPath, newPath))
delFile(oldPath);
}
public static void moveFolder(String oldPath, String newPath) throws Exception {
copyFolder(oldPath, newPath);
delFolder(oldPath);
}
public static void delFolder(String folderPath) {
if ((folderPath == null) || (folderPath.equals("")))
return;
try {
File myFilePath = new File(folderPath);
if ((myFilePath.isDirectory()) && (myFilePath.exists())) {
delAllFile(folderPath);
myFilePath.delete();
}
} catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
}
public static void delAllFile(String path) {
if ((path == null) || (path.equals("")))
return;
File file = new File(path);
if ((!file.exists()) || (!file.isDirectory()))
return;
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator))
temp = new File(path + tempList[i]);
else
temp = new File(path + File.separator + tempList[i]);
if (temp.isFile())
temp.delete();
if (!temp.isDirectory())
continue;
delAllFile(path + File.separator + tempList[i]);
delFolder(path + File.separator + tempList[i]);
}
}
public static void del(String filepath) throws Exception {
if ((filepath == null) || (filepath.equals("")) || (filepath.equals("null")))
return;
try {
File f = new File(filepath);
if ((f.exists()) && (f.isDirectory())) {
if (f.listFiles().length == 0) {
f.delete();
} else {
File[] delFile = f.listFiles();
int i = f.listFiles().length;
for (int j = 0; j < i; j++) {
if (delFile[j].isDirectory())
del(delFile[j].getAbsolutePath());
delFile[j].delete();
}
}
del(filepath);
}
} catch (Exception e) {
throw e;
}
}
public static String read(String fileName, String encoding) {
File f = new File(fileName);
if (!f.exists())
return null;
StringBuffer fileContent = new StringBuffer();
try {
FileInputStream fis = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fis, encoding);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
fileContent.append(line);
fileContent.append(System.getProperty("line.separator"));
}
br.close();
isr.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return fileContent.toString();
}
public static void write(String fileContent, String filePath, String encoding) {
try {
FileOutputStream fos = new FileOutputStream(filePath);
OutputStreamWriter osw = new OutputStreamWriter(fos, encoding);
osw.write(fileContent);
osw.flush();
osw.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void writeTxt(File file, String conent ,boolean append,String charset) {
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,append)));
out.write(conent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void writeTxt(String file, String conent ,boolean append,String charset) {
File f = new File(file);
if(!f.exists())
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
writeTxt(f , conent ,append , charset);
}
public static void writeTxt(String file, String conent ,boolean append)
{
writeTxt(file,conent,append,"utf-8");
}
public static void writeTxt(String file, String conent )
{
writeTxt(file,conent,true, "utf-8");
}
public static void writeTxt(String dir,String fileName, String conent ,boolean append,String charset) {
File dirFile = new File(dir);
if(!dirFile.exists())
dirFile.mkdirs();
File f = new File(dir + fileName);
if(!f.exists())
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f,append),Charset.forName(charset)));
out.write(conent);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
7、远程请求处理(http,soap)
public static String doGet(String url, Map<String, String> param) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpclient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
return resultString;
}
public static String doGet(String url) throws Exception {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, ENCODING);
httpPost.setEntity(entity);
}
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
return doPostJson(url, null, json);
}
public static Map<String,String> post(
Map<String, String> reqData,String reqUrl,String encoding) {
Map<String, String> rspData = new HashMap<String,String>();
LogUtil.writeLog("请求银联地址:" + reqUrl);
HttpClient hc = new HttpClient(reqUrl, 30000, 30000);
try {
int status = hc.send(reqData, encoding);
if (200 == status) {
String resultString = hc.getResult();
if (null != resultString && !"".equals(resultString)) {
Map<String,String> tmpRspData = SDKUtil.convertResultStringToMap(resultString);
rspData.putAll(tmpRspData);
}
}else{
LogUtil.writeLog("返回http状态码["+status+"],请检查请求报文或者请求地址是否正确");
}
} catch (Exception e) {
LogUtil.writeErrorLog(e.getMessage(), e);
}
return rspData;
}
public static final int TIMEOUT = 60;
public static final String ACCEPT_NAME = "Accept";
public static final String ACCEPT = "application/json;charset=UTF-8";
public static String doPostJson(String url, Map<String, String> headerMap, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(TIMEOUT * 1000)
.setConnectTimeout(TIMEOUT * 1000)
.setConnectionRequestTimeout(TIMEOUT * 1000)
.build();
HttpPost httpPost = new HttpPost(url);
httpPost.setProtocolVersion(HttpVersion.HTTP_1_0);
httpPost.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
httpPost.addHeader(ACCEPT_NAME, ACCEPT);
httpPost.setConfig(defaultRequestConfig);
if (headerMap != null) {
Iterator headerIterator = headerMap.entrySet().iterator();
while (headerIterator.hasNext()) {
Entry<String, String> elem = (Entry<String, String>) headerIterator.next();
httpPost.addHeader(elem.getKey(), elem.getValue());
}
}
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostXml(String url, String xml, String soapname) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("SOAPAction", soapname);
StringEntity entity = new StringEntity(xml, ContentType.TEXT_XML);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostXml(String url, String xml) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(xml, ContentType.TEXT_XML);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostWebservice(String url, String xml) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
StringEntity data = new StringEntity(xml, Charset.forName("UTF-8"));
httpPost.setEntity(data);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostWebserviceForSoap11(String url, String xml,String SOAPAction) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("SOAPAction",SOAPAction);
StringEntity data = new StringEntity(xml, Charset.forName("UTF-8"));
httpPost.setEntity(data);
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), ENCODING);
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPostRequest(String url,String xml) {
return doPostRequest(url,xml,"");
}
public static String doPostRequest(String url,String xml,String SOAPAction) {
String result = "";
Map<String, String> requestPropertyMap = new HashMap<>();
requestPropertyMap.put("Content-Type", "text/xml;charset=UTF-8");
requestPropertyMap.put("SOAPAction", SOAPAction);
if ((url == null) || ("".equals(url)))
return result;
try {
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl
.openConnection();
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
for(Map.Entry<String, String> entry : requestPropertyMap.entrySet()) {
httpConn.setRequestProperty(entry.getKey(), entry.getValue());
}
httpConn.setRequestMethod("POST");
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(xml);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result = result + line;
}
in.close();
} catch (Exception e) {
System.out.println(e);
}
return result;
}