Category Archives: Java

「Java入門」JDBCドライバでMySQLへ接続するサンプル

Javaコード:
import java.sql.*;
public class DBConnectDemo {
public static void main(String[] args) {
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/demodb”, “user001”, “123456”);
System.out.println(“DBに接続成功しました。”);
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.out.println(“JDBC Driverのロードに失敗しました。”);
} catch (SQLException e) {
System.out.println(“DBに接続失敗しました。”);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
System.out.println(“DBがクローズしました。”);
}
}
}
}
}

「java入門」 Collections.sort()で List要素をソートする

Javaコード:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ListSort {

public static void main(String[] args) {

List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();

Map<Object, Object> map = new HashMap<Object, Object>();

Map<Object, Object> map1 = new HashMap<Object, Object>();
Map<Object, Object> map2 = new HashMap<Object, Object>();
Map<Object, Object> map3 = new HashMap<Object, Object>();

map.put(“number”, “1.46”);
map1.put(“number”, “2”);
map2.put(“number”, “1.89”);
map3.put(“number”, “1.68”);
list.add(map);
list.add(map1);
list.add(map2);
list.add(map3);

Collections.sort(list, new Comparator<Map<Object, Object>>() {

public int compare(Map<Object, Object> o1, Map<Object, Object> o2) {

int mapval1 = (int)Double.parseDouble((String) o1.get(“number”))*100 ;
int mapval2 = (int)Double.parseDouble((String) o2.get(“number”))*100;
return mapval1 – mapval2;
}
});
System.out.println(list);
}

「Java入門」PreparedStatementでDBを操作する

Javaコード:
String sql = “select * from user where name = ? and age < ?”;
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1,”yamada”);//パラメータ1の設定
pstmt.setInt(2,”30″): //パラメータ2の設定
ResultSet rs = pstmt.executeQuery();//結果を取得

「Java入門」 java.lang.String.lastIndexOf(String str)のサンプル

Javaコード

package itstudy;

public class SearchlastString {

public static void main(String[] args) {
String strOrg = “Hello world ,Hello Reader,Hello Tony”;
int lastIndex = strOrg.lastIndexOf(“Hello”);

if (lastIndex == -1) {
System.out.println(“Hello not found”);
} else {
System.out.println(“Last occurrence of Hello is at index ” + lastIndex);
}
}

}

結果:Last occurrence of Hello is at index 26

「Java」java.text.SimpleDateFormatクラスの使い方

Javaコード:
import java.util.Date;
import java.text.DateFormat;

public class DateDemo{
public static void main(String []args){
Date d = new Date();
String s;

System.out.println(d);

System.out.println(“******************************************”);

/** getDateInstance() */
s = DateFormat.getDateInstance().format(d);
System.out.println(s);

s = DateFormat.getDateInstance(DateFormat.DEFAULT).format(d);
System.out.println(s);

s = DateFormat.getDateInstance(DateFormat.FULL).format(d);
System.out.println(s);

s = DateFormat.getDateInstance(DateFormat.MEDIUM).format(d);
System.out.println(s);

s = DateFormat.getDateInstance(DateFormat.SHORT).format(d);
System.out.println(s);

 

java.text.DateFormat fmt = new java.text.SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
s = fmt.format(new Date());
System.out.println(s);

System.out.println((new java.text.SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”)).format(new Date()));

java.text.DateFormat cft = new java.text.SimpleDateFormat(“yyyyMMddhhmmss”);
s = cft.format(new Date());
System.out.println(s);
}
}

「java入門」複数ファイルを Zip に圧縮するサンプル

Javaコード
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outfilePath));
byte[] buffer = new byte[1024];
int len;

for(String file : files) {
InputStream in = new FileInputStream(file);
out.putNextEntry(new ZipEntry(file.getName()));
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();

}
out.close();

} catch(FileNotFoundException e){

} catch(Exception e){

}

「java」org.apache.commons.beanutilsでmapをobjectに変換するサンプル

javaコード
class DemoCft {

public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;

Object obj = beanClass.newInstance();

org.apache.commons.beanutils.BeanUtils.populate(obj, map);

return obj;
}

public static Map<?, ?> objectToMap(Object obj) {
if(obj == null)
return null;

return new org.apache.commons.beanutils.BeanMap(obj);
}

}

「java」IntrospectorでObject型からMapへキャストするサンプル

Javaコード:
class IntrospectorDemo {

public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
if (map == null)
return null;

Object obj = beanClass.newInstance();

BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
Method setter = property.getWriteMethod();
if (setter != null) {
setter.invoke(obj, map.get(property.getName()));
}
}

return obj;
}

public static Map<String, Object> objectToMap(Object obj) throws Exception {
if(obj == null)
return null;

Map<String, Object> map = new HashMap<String, Object>();

BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase(“class”) == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter!=null ? getter.invoke(obj) : null;
map.put(key, value);
}

return map;
}

}

「Java入門」ZipOutputStreamでファイルをzipに圧縮するコード

javaコード
private void FiletoZipFunc(List<File> fileList) throws IOException{
if(null != fileList && !fileList.isEmpty()){
byte[] buf = new byte[1024];
String url = REAL_PATH + “/” + EXPORT_URL + “/” + TABLE_NAME;
String fi = url + “/” + TABLE_NAME + “.zip”;
FileOutputStream os = new FileOutputStream(fi);
ZipOutputStream zipOut = new ZipOutputStream(os);
for(File file : fileList){
FileInputStream in = new FileInputStream(file);
zipOut.putNextEntry(new ZipEntry(file.getName()));
int len;
while((len = in.read(buf)) > 0){
zipOut.write(buf, 0, len);
}
zipOut.closeEntry();
in.close();
file.delete();//ファイル削除
}
zipOut.close();
}
}

「Java入門」文字列をjsonデータへ変換するコード

Javaコード
private static String stringToJson(String s) {
if (s == null) {
return “”;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case ‘”‘:
sb.append(“\\\””);
break;
case ‘\\’:
sb.append(“\\\\”);
break;
case ‘\b’:
sb.append(“\\b”);
break;
case ‘\f’:
sb.append(“\\f”);
break;
case ‘\n’:
sb.append(“\\n”);
break;
case ‘\r’:
sb.append(“\\r”);
break;
case ‘\t’:
sb.append(“\\t”);
break;
case ‘/’:
sb.append(“\\/”);
break;
default:
if (ch >= ‘\u0000’ && ch <= ‘\u001F’) {
String ss = Integer.toHexString(ch);
sb.append(“\\u”);
for (int k = 0; k < 4 – ss.length(); k++) {
sb.append(‘0’);
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}
return sb.toString();
}