| TIPS |
| ImageIOでBufferedImageを扱う |
//読み込み
BufferedImage image = ImageIO.read(file);
//書き込み
ImageIO.write(image, "jpg", file);
|
| Listから配列にする |
//List#toArray()を使う
String[] b = list.toArray(new String[0]);
|
| 配列からListにする |
//Arrays#asList()を使う
List list = Arrays.asList(a);
List list = Arrays.asList(new String[]{"a","b"});
|
| Stringで文字が含まれるを確認する |
//indexOfを使う
if("abcde".indexOf("bc") != -1) //あり
//containsを使う
if("abcde".contains("bc")) //あり
#containsは内部的にindexOfを使っているので分かりやすさからcontainsの方が良いかと。
|
| Listの項目を結合して文字列にする |
List list = ...
String joinText = String.join(",", list); // xxx,xxx,xxxとなる
|
| Listなどで空をisEmptyで確認する |
List<String> list = new ArrayList<>();
if(list.size() == 0) //これでも空リストだけど
if(list.isEmpty()) //こちらの方がわかりやすくないですか
|
| (JSoup)使い方 |
Document doc = JSoup.parse(HTML);
Elements elements = doc.select(“table”); //1個しかなくても配列になる
Element el = elements.get(0);
el.text();
|
| (JSoup)Element#textと#ownTextの違い |
Element#text 配下のタグの全てのテキストを取得する
Element#ownText 配下があっても自身のテキストのみを取得する
|
| 経過時間を計算して表示する |
//System.currentTimeMillis()で現在の時間を取得する
//Apache-CommonsのDurationFormatUtils.formatPeriod()を使う
long startTime = System.currentTimeMillis();
Thread.sleep(1000);
long endTime = System.currentTimeMillis();
String time = DurationFormatUtils.formatPeriod(startTime, endTime, “HH:mm:ss.SSS”);
|
| (Apache-Commons)FTPでファイル転送したい |
Apache-CommonsのFTPClientクラスを使う
org.apache.commons.net.ftp.FTPClient
|
| (Class)文字列でクラスをロードしてインスタンスを作成する |
Class clazz = Class.forName(“MyClass”);
MyClass myclass = (MyClass) clazz.newInstance();
|
| 外部プログラム起動 |
Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c dir");
|
| [File]Exceptionが発生しないメソッド |
java.io.File
#delete
#mkdir
$mkdirs
#renameTo
#setLastModified
#setReadOnly
|
| byte[]をInputStream |
byte[] data = ...
InputStream in = new ByteArrayInputStream(data);
|
| BigDecimalの初期化 |
//BigDecimalを0で初期化する場合、インスタンスで初期化しない
//BigDecimalはイミュータブル(変更不可)なので同じ値は同じ参照先になり
//メモリ節約になります
BigDecimal b = new BigDecimal(0); //×
BigDecimal b = BigDecimal.valueOf(0); //△ ベター
BigDecimal b = BigDecimal.ZERO; //ゼロならベスト
|
| @Override |
@Overrideアノテーションをつけると、明示的にオーバーライドしていること明確になり
スーパークラスに該当するメソッドがない(=オーバーライドでない)場合はコンパイルエラーになります。
|
| 予約語 |
| private |
public |
protected |
class |
try |
| catch |
finally |
if |
else |
for |
| while |
extends |
implements |
import |
package |
| interface |
abstract |
void |
int |
boolean |
| float |
double |
char |
new |
null |
| static |
return |
break |
short |
long |
| throw |
throws |
case |
do |
final |
| goto |
instanceof |
true |
false |
default |
| continue |
switch |
for |
|
|
|
| if |
if(判定){
}else if(判定){
}else{
}
|
| for |
for(int idx = 0 ; idx < 5 ; idx++){
if(idx == 4) break;
if(idx == 2) continue;
}
|
| for-each |
String[] cols = "1,2,3,4,5".split(",");
for(String col : cols){
}
|
| try |
try{
}catch(Exception ex){
}finally{
}
|
| テキストファイルを一気読み |
Path path = Paths.get("textfile");
String text = java.nio.Files.readString(path, Charset.forName("UTF-8"));
|
| バイナリファイルを一気読み |
Path path = Paths.get("file");
byte[] data = java.nio.Files.readAllBytes(path);
|
| base64エンコード |
Path path = Paths.get("file");
byte[] data = java.nio.Files.readAllBytes(path);
String encoded = java.util.Base64.getEncoder().encodeToString(data);
|
| try-resources |
try(InputStream in = new FileInputStream("ファイル")){
while((byte b = in.read()) != null){
}//while
}catch(IOException ex){
}
//inのclose処理が自動で行なわれる
//AutoCloseインターフェイスが実装されていないとダメ
|
| 拡張for |
List<String> list = new ArrayList<>(Arrays.asList(new String[]{"a","b","c"}));
-- こっちよりも
for(Iterator<String> ite=list.iterator(); ite.hasNext(); ){
System.out.println(ite.next());
}
-- こっちを使いましょう
for(String str : list){
System.out.println(s);
}
|
| [Eclipse]ファイルとエクスプローラと同期 |
開いているファイルをエクスプローラで表示(ツリー展開)するには
エクスプローラの上部の[←→]を選択状態にする
|
| HashMapのコピー |
HashMap copyto = new HashMap<>(copyfrom);
|
| HashMapの操作 |
Map map = new HashMap();
// キーの有無
if (map.containsKey(key)) {}
// ループ
for (key : map.KeySet()) {}
|
| Path結合 |
Path path = Paths.get("C:","a","b","c"); //C:/a/b/c
|
| pathで存在チェック |
if(Files.exists(path)){
//あり
}
|
| pathでフォルダ作成 |
Files.createDirectories(path);
|
| pathでファイルコピー |
Files.copy(path1, path2);
|
| String->BigDecimal |
BigDecimal bigdecimal = new BigDecimal("123.45");
|
| String#replaceAllで除外 |
String text = ...;
// 改行(¥r¥n/¥r/¥n)、タブ(¥t)、円記号(¥)を除去する
text = text.replaceAll("¥¥r¥¥n|¥¥r|¥¥n|¥¥t|¥¥¥¥", "");
|
| OpenCSV |
//読み込み
CSVParser parser = new CSVParserBuilder().withSeparator(',').withQuoteChar('"').build();
InputStreamReader isreader = new InputStreamReader(new FileInputStream(filepath), "UTF-8");
CSVReader reader = new CSVReaderBuilder(isreader).withCSVParser(parser).build();
String[] record = null;
while ((record = reader.readNext()) != null) {
System.out.println(record[0] + "," + record[1]);
}
//書き込み
CSVParser parser = new CSVParserBuilder().withSeparator(',').withQuoteChar('"').build();
OutputStreamWriter osw = new OutputStreamReader(new FileOutputStream(filepath), "UTF-8");
ICSVWriter writer = new CSVWriterBuilder(osw).withParser(parser).withLineEnd("¥r¥n").build();
for(String[] line : lines) {
writer.writeNext(line);
}
writer.flush();
writer.close();
|
| [POI]色の名前 |
| 色 |
| BLACK |
| WHITE |
| RED |
| BRIGHT_GREEN |
| BLUE |
| YELLOW |
| PINK |
| TURQUOISE |
| DARK_RED |
| GREEN |
| DARK_BLUE |
| DARK_YELLOW |
| VIOLET |
| TEAL |
| GREY_25_PERCENT |
| GREY_50_PERCENT |
| CORNFLOWER_BLUE |
| MAROON |
| LEMON_CHIFFON |
| ORCHID |
| CORAL |
| ROYAL_BLUE |
| LIGHT_CORNFLOWER_BLUE |
| SKY_BLUE |
| LIGHT_TURQUOISE |
| LIGHT_GREEN |
| LIGHT_YELLOW |
| PALE_BLUE |
| ROSE |
| LAVENDER |
| TAN |
| LIGHT_BLUE |
| AQUA |
| LIME |
| GOLD |
| LIGHT_ORANGE |
| ORANGE |
| BLUE_GREY |
| GRAY_40_PERCENT |
| DARK_TEAL |
| SEA_GREEN |
| DARK_GREEN |
| OLIVE_GREEN |
| BROWN |
| PLUM |
| INDIGO |
| GREY_80_PERCENT |
| AUTOMATIC |
|
| ファイル内容を簡単に読み込む |
Path path = Paths.get("ファイルパス");
byte[] data = Files.readAllBytes(path);
|
| [文字列]format |
// String.format
String.format("%3$d:%1$d:%2$d%n",11,22,33); // 33:11:22
Date date = new Date();
String str = String.format("%1$tY/%1$tm/%1$td%n", date.getTime());
|
| 色々contains |
String target_str = "a";
// String[] / List
if (Arrays.asList(new String[]{"a","b","c"}).contains(target_str)) xxxx
// String
if ("abcdef".contains(target_str)) xxxx
|
| [Apche PDFBox] |
・セキュリティ
AccessPermissionクラス
AccessPermission ap = new AccessPermission();
ap.setCanPrint(false); // 印刷可否
doc.protect(ap); // セキュリティを反映
・PDF読み込み
PDFDocument#load(PDF);
・画像化
PDFRenderer
#renderImageWithDPI();
・PDF結合
PDFMergerUtility
#addSource()
#setDestinationFileName()
#mergeDocuments()
|
| lpadding |
public static String lpadding(String pTarget, int pLength, char pPadChar) {
int targetLength = pTarget.length();
if (targetLength >= pLength) {
return pTarget;
}
StringBuilder sb = new StringBuilder(pLength);
for (int i = targetLength; i < pLength; i++) {
sb.append(pPadChar);
}
sb.append(pTarget);
return sb.toString();
}
|