Java常用ツール方法使用心得
31550 ワード
ロット当たり1万処理ビッグデータ集合
このバッチ処理は主にmysqlデータ処理に用いられる
List list = new ArrayList<>();
for(int i = 0 ;i< 51254;i ++){
list.add("pp"+i);
}
int size = list.size();
for (int i = 0; i < size; i+=Config.EVERY_NUM) {
int suffix = Config.EVERY_NUM;
if(i+Config.EVERY_NUM > size){
suffix = size - i;
}
List sublist = list.subList(i,i+suffix);
System.out.println(sublist.size());
}
しゅつりょく
10000
10000
10000
10000
10000
1254
文字列が数値かどうかを判断する
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
またはStringUtilsが持つ関数を使用します
public static boolean isNumeric(String str){
for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
}
urlのipを取得
try {
String bankurl = "https://directbank.czbank.com/APPINSPECT/finance/creditCardApyOnlineCardSel.jsp";
URL url = new URL(bankurl);
InetAddress[] ips = InetAddress.getAllByName(url.getHost());
for (InetAddress ip : ips) {
System.out.println(ip.toString());
System.out.println("Address:" + ip.getHostAddress());
System.out.println("Name:" + ip.getHostName());
}
}catch (Exception e){
e.printStackTrace();
}
ここでipを取得するのは実際にipに着くべきで、dnsを通らないで、cdnを迂回します
フォルダの展開、圧縮
JAvaが持参した圧縮apiは普通のファイルしか操作できません.暗号化されたzipファイルを操作するには、
<dependency>
<groupId>net.lingala.zip4jgroupId>
<artifactId>zip4jartifactId>
<version>1.3.2version>
dependency>
具体的なコードは、zip 4 j–パスワード付きzipパッケージの処理
public static void unzip(File zipFile, String dest, String passwd) throws ZipException {
ZipFile zFile = new ZipFile(zipFile); // ZipFile .zip
zFile.setFileNameCharset("GBK"); // , GBK
if (!zFile.isValidZipFile()) { // .zip , 、 zip 、
throw new ZipException(" , .");
}
File destDir = new File(dest); //
if (destDir.isDirectory() && !destDir.exists()) {
destDir.mkdir();
}
if (zFile.isEncrypted()) {
zFile.setPassword(passwd.toCharArray()); //
}
zFile.extractAll(dest); // ( )
}
zipファイルを解凍するパスワードを持たない指定フォルダJavaにzipファイルを解凍する[指定ディレクトリへ]
/**
*
*
* @param zipPath
* @param descDir
*/
public static void unZipFiles2(String zipPath, String descDir) throws IOException {
unZipFilesNew(new File(zipPath), descDir);
delFolder(descDir + "/__MACOSX");
}
/**
*
* ,
*
* @param zipFile zip
* @param descDir
*/
@SuppressWarnings("rawtypes")
public static void unZipFilesNew(File zipFile, String descDir) throws IOException {
ZipFile zip = new ZipFile(zipFile, Charset.forName("UTF-8"));//
String name = zip.getName().substring(zip.getName().lastIndexOf('\\') + 1, zip.getName().lastIndexOf('.'));
File pathFile = new File(descDir);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
for (Enumeration extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + "/" + zipEntryName).replaceAll("\\*", "/");
// ,
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// , ,
if (new File(outPath).isDirectory()) {
continue;
}
//
// System.out.println(outPath);
FileOutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
System.out.println("****************** ********************");
return;
}
圧縮ファイルにパスワードがない
/**
*
*
* @param dirPath
* @param zipName http://www.jb51.net/article/115212.htm
*/
public static void zipFiles(String dirPath, String zipName) {
List srcfile = getFiles(dirPath);
byte[] buf = new byte[1024];
try {
//ZipOutputStream :
File zipFile = new File(zipName);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i < srcfile.size(); i++) {
File file = new File(srcfile.get(i));
FileInputStream in = new FileInputStream(file);
out.putNextEntry(new ZipEntry(file.getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
System.out.println(" .");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
コマンドラインコマンドの実行
Runtime.getRuntime().exec()リダイレクトコマンドの実行方法
private void moveFile(String srcFilePath, String destFilePath) {
try {
Runtime runtime = Runtime.getRuntime();
String[] cmd = {"sh", "-c", "mv " + srcFilePath + " " + destFilePath};
Process outputCsvDecrypt = runtime.exec(cmd);
int outputExitVal = outputCsvDecrypt.waitFor();
System.out.println(" " + outputExitVal);
if (outputExitVal == 0) {
System.out.println(srcFilePath + " ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
SimpleDateFormat月日0を表示しない
https://blog.csdn.net/KingWTD/article/details/48089111
SimpleDateFormat format = new SimpleDateFormat("yyyyMd");
System.out.println(format.format(new Date()));
2018511
List漢字ソート
https://blog.csdn.net/jky_yihuangxing/article/details/50736154
List list=new ArrayList<>();
list.add(" ");
list.add(" ");
list.add(" ");
list.add(" ");
list.add(" ");
Collections.sort(list, Collator.getInstance(java.util.Locale.CHINA));
空のフォルダを削除
/**
*
* @param folderPath
*/
public static void delFolder(String folderPath) {
try {
// File
File myFilePath = new File(folderPath);
myFilePath.delete(); //
} catch (Exception e) {
e.printStackTrace();
}
}
フォルダの下にあるすべてのファイル名を取得
Java-あるディレクトリの下にあるすべてのファイル、フォルダ、および3種類のファイルパスからファイル名を取得する方法
public static ArrayList getFiles(String path) {
ArrayList files = new ArrayList();
File file = new File(path);
File[] tempList = file.listFiles();
for (int i = 0; i < tempList.length; i++) {
if (tempList[i].isFile()) {
files.add(tempList[i].toString());
}
}
return files;
}
文字列から数値を抽出
JAva文字列から数値を抽出
String regEx = "[^0-9]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
String id = m.replaceAll("").trim();
System.out.println("--------------id" + id);
以上の入力は
group.data163.data
または
group.data163
出力は
163
最後に置換するには、replaceFirstメソッドを模倣します.
https://stackoverflow.com/questions/2282728/java-replacelast
public static String replaceLast(String text, String regex, String replacement) {
return text.replaceFirst("(?s)(.*)" + regex, "$1" + replacement);
}
public static void main(String[] args) {
System.out.println(replaceLast("foo AB bar AB AB car AB done", "AB", "--"));
}
以上の出力内容は
foo AB bar AB AB car -- done
小数を2桁とる
int a = 2;
double b = 10000;
DecimalFormat decimalFormat=new DecimalFormat("######0.00");
System.out.println(decimalFormat.format(a/b*100)+"%");
:0.02%
日付が一定の日付内かどうかを判断する
String dateStr= "02/11/2017 18:36:57";
String startDate = "2017-02-11";
String endDate = "2017-02-13";
System.out.println(Utils.getFormatDate(dateStr,startDate,endDate));
:
public static boolean getFormatDate(String dateStr, String inputDate) {
boolean isIncurrentDay = false;
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
String fileDate = format2.format(format.parse(dateStr));
if (fileDate.equals(inputDate)) {
System.out.println(" ");
isIncurrentDay = true;
} else {
System.out.println(" ");
isIncurrentDay = false;
}
} catch (ParseException e) {
e.printStackTrace();
}
return isIncurrentDay;
}
public static boolean getFormatDate(String dateStr, String startDate, String endDate) {
boolean isInDuration = false;
try {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
Date dateS = format2.parse(format2.format(format.parse(dateStr)));
Date startS = format2.parse(startDate);
Date endS = format2.parse(endDate);
if (!dateS.after(endS) && !dateS.before(startS)) {
System.out.println(" ");
isInDuration = true;
} else {
System.out.println(" ");
isInDuration = false;
}
} catch (ParseException e) {
e.printStackTrace();
}
return isInDuration;
}
プロジェクトプロファイルの変数値の取得
第1種
Properties property = new Properties();
try {
property.load(new FileInputStream(" "));
} catch (IOException e) {
e.printStackTrace();
}
String value = property.getProperty(" key");
2つ目は、おすすめ
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("email");
String keystore = bundle.getString("mysql.decrystore"); //
txtファイルの最後の行のファイル内容を上書きして追加する
public static void rewriteendline(String filepath, String string)
throws Exception {
RandomAccessFile file = new RandomAccessFile(filepath, "rw");
long len = file.length();
long start = file.getFilePointer();
long nextend = start + len - 1;
int i = -1;
file.seek(nextend);
byte[] buf = new byte[1];
while (nextend > start) {
i = file.read(buf, 0, 1);
if (buf[0] == '\r') {
file.setLength(nextend - start);
break;
}
nextend--;
file.seek(nextend);
}
file.close();
writeendline(filepath, string);
}
public static void writeendline(String filepath, String string)
throws Exception {
RandomAccessFile file = new RandomAccessFile(filepath, "rw");
long len = file.length();
long start = file.getFilePointer();
long nextend = start + len - 1;
byte[] buf = new byte[1];
file.seek(nextend);
file.read(buf, 0, 1);
if (buf[0] == '
')
file.writeBytes(string);
else
file.writeBytes("\r
" + string);
file.close();
}
文字列から携帯電話番号を取得
/**
* 11 , ,
* @param text
* @return
*/
public static String getPhone11(String text){
Pattern pattern = Pattern.compile("(?);
Matcher matcher = pattern.matcher(text);
StringBuffer bf = new StringBuffer(64);
while (matcher.find()) {
bf.append(matcher.group()).append(",");
}
int len = bf.length();
if (len > 0) {
bf.deleteCharAt(len - 1);
}
return bf.toString();
}
/**
* , 12
* @param str
*/
public static void checkCellphone(String str){
//
Pattern pattern = Pattern.compile("((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}");
// 。
Matcher matcher = pattern.matcher(str);
//
while(matcher.find()){
//
System.out.println(" :"+matcher.group());
}
}
/**
**/
private static String checkNum(String num){
if(num == null || num.length() == 0){return "";}
Pattern pattern = Pattern.compile("(?);
Matcher matcher = pattern.matcher(num);
StringBuffer bf = new StringBuffer(64);
while (matcher.find()) {
bf.append(matcher.group()).append(",");
}
int len = bf.length();
if (len > 0) {
bf.deleteCharAt(len - 1);
}
return bf.toString();
}
private static boolean isNumLegal(String str) throws PatternSyntaxException {
String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(str);
return m.matches();
}