Monthly Archives: 1月 2016

java開発でCollectionUtilsとArrayUtilsの使い方

導入jar

commons-collections-3.2.1.jar
commons-lang3-3.4.jar

コード下記

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
public class CollectTest {

/**
* @param args
*/
public static void main(String[] args) {
String[] arrTestA = new String[] { “31”, “32”, “33”, “34”, “35”, “36” };
String[] arrTestB= new String[] { “16”, “34”, “36”, “39”, “40”, “51” };

List list_a = Arrays.asList( arrTestA );
List list_b = Arrays.asList( arrTestB);

Collection union = CollectionUtils.union( list_a ,list_b ); //和集合
Collection intersection = CollectionUtils.intersection( list_a , list_b); //積集合
Collection disjunction = CollectionUtils.disjunction( list_a , list_b ); //排他集合
Collection subtract = CollectionUtils.subtract( list_a , list_b ); //差集合

Collections.sort ((List<String>) union );
Collections.sort( (List<String>) intersection );
Collections.sort( (List<String>) disjunction );
Collections.sort( (List<String>) subtract );
System.out.println( “TestA: ” + ArrayUtils.toString( list_a.toArray( ) ) );
System.out.println( “TestB: ” + ArrayUtils.toString( list_b.toArray( ) ) );
System.out.println( “和集合を返す: ” + ArrayUtils.toString( union.toArray( ) ) );
System.out.println( “積集合を返す : ” +ArrayUtils.toString( intersection.toArray( ) ) );
System.out.println( “排他的な和集合を返す : ” +ArrayUtils.toString( disjunction.toArray( ) ) );
System.out.println( “差集合を返す: ” + ArrayUtils.toString( subtract.toArray( ) ) );

}

}

実行結果

集合A: {31,32,33,34,35,36}
集合B: {16,34,36,39,40,51}
和集合を返す: {16,31,32,33,34,35,36,39,40,51}
積集合を返す : {34,36}
排他的な和集合を返す : {16,31,32,33,35,39,40,51}
差集合を返す: {31,32,33,35}

javaでテキストファイルを読み込むサンプル

コード下記
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Filetoread {
public static String readFile(String fileName) {
String output = “”;

File file = new File(fileName);

if(file.exists()){
if(file.isFile()){
try{
BufferedReader input = new BufferedReader (new FileReader(file));
StringBuffer buffer = new StringBuffer();
String text;

while((text = input.readLine()) != null)
buffer.append(text +”\n”);

output = buffer.toString();
}
catch(IOException ioException){
System.err.println(“ファイルエラー!”);

}
}
else if(file.isDirectory()){
String[] dir = file.list();
output += “ディレクトリのコンテンツ:\n”;

for(int i=0; i<dir.length; i++){
output += dir[i] +”\n”;
}
}
}
else{
System.err.println(“存在しません!”);
}
return output;
}
public static void main(String[] args) {
String str = readFile(“D:/startnews24.txt”);

System.out.print(str);
}

}

Java で MD5 文字列を求めるプログラム

コード下記

public class MD5 {

public static String encode(byte[] source) {
String s = null;
char hexDigits[] = { ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’ };
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance(“MD5”);
md.update(source);
byte tmp[] = md.digest();
char str[] = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = tmp[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
s = new String(str);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}

public static String getMD5(String source) {
return (source == null || “”.equals(source)) ? “” : getMD5(source);
}
}

Java におけるプロキシ経由のリモートipを取得する方法

コード下記
public static String getReaIP_Te(HttpServletRequest request) {
String strip = request.getHeader(“X-Real-IP”);
if (StringUtil.isEmpty(strip) || “unknown”.equalsIgnoreCase(strip)) {
strip = request.getHeader(“X-Forwarded-For”);
}
if (StringUtil.isEmpty(strip) || “unknown”.equalsIgnoreCase(strip)) {
strip = request.getRemoteAddr();
}
return strip;
}

MySQL一般的コマンドでデータベース操作まとめ

1.起動方法
①service:service mysqld start
② mysqld:/etc/init.d/mysqld start
③ safe_mysqld:safe_mysqld&

2.停止方法
①service:service mysqld stop
② mysqld :/etc/init.d/mysqld stop
③mysqladmin shutdown

3.再起動方法
①service:service mysqld restart
②mysqld:/etc/init.d/mysqld restart

JavaでINIファイルを削除するサンプルソース

コード下記
public static void DeleteINI(String file, String sect, String key, String value) {
BufferedReader input = null;
PrintWriter output = null;
try {
FileOutputStream foslock = new FileOutputStream(file + “.lock”); FileLock filelock = null;
try {
filelock = foslock.getChannel().lock();
} catch (IOException e) {
}
String file_cont = “”;
boolean replaced = false;
File fh = new File(file);
if (fh.exists()) {
input = new BufferedReader(new FileReader(file));
String my_line;
Pattern p = Pattern.compile(“^\\[” + sect + “\\]” + key + “=(.*)$”);
while ((my_line = input.readLine()) != null) {
Matcher m = p.matcher(my_line);
if (m.find()) {
// DELETE
} else if (my_line.equals(“%>”)) {
// IGNORE
} else {
file_cont += my_line + “\r\n”;
}
}
input.close();
} else {
file_cont += “<%” + “\r\n”;
}
file_cont += “%>”;
output = new PrintWriter(new FileOutputStream(file));
if (output != null) {
output.print(file_cont);
output.close();
}
if (filelock != null) filelock.release();
foslock.close();
File fhlock = new File(file + “.lock”);
if (fhlock.exists()) fhlock.delete();
} catch (FileNotFoundException e) {
if (input != null) try { input.close(); } catch (IOException ee) { ; }
if (output != null) try { output.close(); } catch (Exception ee) { ; }
} catch (IOException e) {
if (input != null) try { input.close(); } catch (IOException ee) { ; }
if (output != null) try { output.close(); } catch (Exception ee) { ; }
}
}

JavaでHtmlの特殊符号文字列のencodeとdecodeのサンプルコード

Javaコード下記
public static String encode(String value) {
String htmltext = “”;
if (value != null) htmltext = “” + value;
htmltext = htmltext.replaceAll(“\\&”, “&amp;”);
htmltext = htmltext.replaceAll(“<“, “&lt;”);
htmltext = htmltext.replaceAll(“>”, “&gt;”);
htmltext = htmltext.replaceAll(“\””, “&quot;”);
return htmltext;
}
public static String decode(String value) {
String htmltext = “”;
if (value != null) htmltext = “” + value;
htmltext = htmltext.replaceAll(“\\&quot;”, “\””);
htmltext = htmltext.replaceAll(“\\&gt;”, “>”);
htmltext = htmltext.replaceAll(“\\&lt;”, “<“);
htmltext = htmltext.replaceAll(“\\&amp;”, “&”);
return htmltext;
}

Java開発でObserverの観察対象を定義するサンプルプログラム

コード下記:
import java.util.Observable;
public class SubjectObservable extends Observable{
public void changeDate(){
System.out.println(“日付を変更した”);
this.setChanged();
}
}
class Subject{
SubjectObservable f = new SubjectObservable();
public void registerObserver(java.util.Observer o){
f.addObserver(o);
}
void changeSubject(){
f.changeDate();
//観察者に通知
f.notifyObservers();
}
}
//観察者1
class SubjectObserver implements java.util.Observer {
public void update(Observable o, Object arg) {
SubjectObservable subject=(SubjectObservable) o;
System.out.println(“観察者1は仕事中 “);
}
}
//観察者2
class SubjectObserver2 implements java.util.Observer {
public void update(Observable o, Object arg) {
SubjectObservable subject=(SubjectObservable) o;
System.out.println(“観察者2は仕事中”);
}
}
main処理コード
public static void main(String args[]){
Subject sbt = new Subject();
SubjectObserver or = new SubjectObserver();
SubjectObserver2 or2 = new SubjectObserver2();
sbt.registerObserver(or2);
sbt.registerObserver(or);
sbt.changeSubject();
}

Java開発でfinalize()を実装するプログラム

コード下記:
public class FinalCheck {
public static void main(String[] args){
Booksell novels = new Booksell(true,”novels”);
novels.checkIn();
novels = null;
new Booksell(true,”null”);
Booksell zazhi = new Booksell(true,”zazhi”);
System.gc();
}
}
class Booksell{
boolean checkedflag = false;
String name=””;
Booksell(boolean checkout,String name){
this.checkedflag = checkout;
this.name = name;
}
void checkIn(){
System.out.println(name+” checkIn”);
checkedflag = false;
}

protected void finalize(){
System.out.println(name+” finalize is working “);
if(checkedflag){
System.out.println(name+”エラー: check out”);
}
}
}

Javaでリフレクションを利用してprivateフィールドを取得するサンプルコード

コード下記
public class GetPriAtt {
public static void main(String args[]){
Kyu t = new Kyu();
Class temp = t.getClass();
Field f;
try {
f = temp.getDeclaredField(“key”);
f.setAccessible(true);
System.out.println(f.get(t));
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Kyu{
private String key=null;
public Kyu(){
key = “778”;
}
}

2 / 3123