JSON (JavaScript Object Notation)
- 가벼운 데이터 변환 포멧

Sample data
{"result":"success", "value":"0", "list":[...]}


Simple Code
import org.codehaus.jettison.json.JSONObject;
import org.apache.cxf.helpers.IOUtils;

JSONObject json = new JSONObject(IOUtils.toString(in));
System.out.println(json.getString("result"));
System.out.println(json.getString("value"));

List Code
JSONObject jsonObject = new JSONObject(IOUtils.toString(in));
JSONArray jsonArray = jsonObject .getJSONArray("list");

for(int i = 0 ; i < jsonArray .length() ; i++){
    JSONObject listJson= jsonArray .getJSONObject(i);
    System.out.println(listJson.getString("result"));
    System.out.println(listJson.getString("value"));
}



Posted by 짱가쟁이
2010. 7. 1. 13:31
파일에서 한줄씩 읽어서 String array 로 반환하자.
/**
 * 파일 한줄씩 읽기
 * 
 * @param file
 * @return
 * @throws IOException
 */
public static String[] readLine(File file) throws IOException {

    BufferedReader reader     = null;
    String[] result         = null;
    
    try {
        reader     = new BufferedReader(new FileReader(file));
        List<String> list         = new ArrayList<String>();

        // while(reader.read() != -1) { 첫번째 케릭터를 읽고 무시하니 line을 제대로 읽지 못함.
        while(reader.ready()) { // 변경
            String content = reader.readLine();
            
            if(content != null && !"".equals(content.trim())) {
                list.add(content);
            }
        }
        
        if(list.size() > 0) {
            result = new String[list.size()];
            for(int i = 0;i<list.size();i++) {
                result[i] = list.get(i);
            }
        }
    } catch(IOException ioe) {
        throw ioe;
    } finally {
        if(reader != null) reader.close();
    }

    return result;
}

위에 저넘을 사용하려다 문제가 발생함.. 파일을 읽을 때 얖에 2byte 빼고 데이터를 가져오더라.. 이유는 찾아보기 귀찮고 일은 바쁘고.. 그냥 새로 맹갔다.
댓글 남겨주신 GG님의 의견을 반영했습니다. 도움 감솨드립니다 ^^


/**
     * 파일 한줄씩 읽기
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String[] readLine1(File file) throws IOException {

        FileInputStream fstream = null;
        DataInputStream in        = null;
        BufferedReader br         = null;
       
        String[] result               = null;
       
        try {
            fstream = new FileInputStream(file);
            in = new DataInputStream(fstream);
            br = new BufferedReader(new InputStreamReader(in));
           
            List<String> list         = new ArrayList<String>();
           
            String strLine;
           
            while ((strLine = br.readLine()) != null)   {
                if(strLine != null && !"".equals(strLine.trim())) {
                    list.add(strLine);
                }
            }

            if(list.size() > 0) {
                result = new String[list.size()];
                for(int i = 0;i<list.size();i++) {
                    result[i] = list.get(i);
                }
            }
                       
        } catch(IOException ioe) {
            throw ioe;
        } finally {
            if(br != null) br.close();
            if(in != null) in.close();
            if(fstream != null) fstream.close();
        }

        return result;
    }

고민하기 싫은데. 대체 뭔 차이여.. 누가 설명좀 해주면 안될까?? 쩌ㅃ~



'java > util' 카테고리의 다른 글

[util] - byte to hex string  (0) 2010.09.07
[java] - replaceNull  (0) 2010.07.05
[java] - File read  (0) 2010.07.01
[java] - byte array to image  (0) 2010.06.30
[java] - 소수점 자르기 (duble type)  (0) 2010.06.30
Posted by 짱가쟁이
2010. 7. 1. 13:05
요넘 파일 가지고 놀때는 항상 API를 뒤적이더라.. 다른 넘들은 재사용을 잘하면서 요넘들은 뭐가 문제일까?

파일 전체를 문자열로 읽는 함수
/**
     * 파일 전체 읽기
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String read(File file) throws IOException {
       
        FileInputStream fis     = null;
        byte[]             buffer     = null;
       
        try {
            fis     = new FileInputStream(file);
            buffer     = new byte[fis.available()];       
            fis.read(buffer, 0, fis.available());
        } catch(IOException e) {
            throw e;
        } finally {
            if(fis != null) fis.close();
        }
       
        return new String(buffer);
    }

'java > util' 카테고리의 다른 글

[java] - replaceNull  (0) 2010.07.05
[java] - File readLine  (2) 2010.07.01
[java] - byte array to image  (0) 2010.06.30
[java] - 소수점 자르기 (duble type)  (0) 2010.06.30
[java] - base54 String decode  (0) 2010.06.30
Posted by 짱가쟁이
데이터 규약(data contract) 작성을 위해서 사용되는 XSD 추론도구중 하나로 웹 서비스를 개발할때나 XML을 가지고 놀때 사용하면 좋음.

사용방법
java -jar trang.jar EvaluateHandRequest.xml, EvaluateHandResponse.xml PokerType.xsd

Posted by 짱가쟁이
2010. 6. 30. 14:27
자바로 UI를 개발하면 기존에 사용하던 윈도우 포맷과 틀려서 거부감이 들때가 있었다. 뭐 그래서 SWT를 찾아 공부도 하고했지만.. look and feel 이라는 넘이 존재하더라.. 이넘 언제부터 나온건지 모름..

기본적으로 윈도우 포맷에 맞춰서 보여주는 코드..

Example
try {
// Set cross-platform Java L&F (also called "Metal")
    UIManager.setLookAndFeel(
        UIManager.getSystemLookAndFeelClassName());
}
catch (UnsupportedLookAndFeelException e) {
   // handle exception
}
catch (ClassNotFoundException e) {
   // handle exception
}
catch (InstantiationException e) {
   // handle exception
}
catch (IllegalAccessException e) {
   // handle exception
}


Posted by 짱가쟁이
우선은 3.5 와 3.6은 차이가 좀 있는 듯.. 예전에 만들어 놓은 코드를 사용하려고 했더니. 쩌ㅃ~  WorkFactory(??) 가 없다고 동작을 안함. 그렇다고 3.5를 다시 다운받고 올려보자니. 귀찮고..

우선은 2007 이상 버전의 Excel을 가지고 놀아야 할텐데.. 이때 사용할 넘이 "XSSF" 란 넘이다.
Example
File theFile = fileChooser.getSelectedFile();

try {
    XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(theFile));
    XSSFSheet sheet = wb.getSheetAt(0);

    String[] phoneNumbers = new String[sheet.getPhysicalNumberOfRows()];

    for(int i = 0;i<sheet.getPhysicalNumberOfRows();i++) {
         XSSFRow row = sheet.getRow(i);
         phoneNumbers[i] = row.getCell(0).getStringCellValue();
    }
} catch (IOException ex) {
    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}        

대충 보면 첫번째 컬넘에 있는 데이터만 가지고 오는 넘임.. 참고로.. 2007 이전 버전은 HSSF(??) 를 사용하면 됨. 코드는 똑같을 듯..

'java > excel' 카테고리의 다른 글

[excel] - Apache POI 를 이용하여 Excel 가지고 놀기  (0) 2010.06.29
Posted by 짱가쟁이


요넘 예전에 공부하다가 대충 훌터보고 넘겼었는데.. 드디에 사용하게 되는구만..

가끔 엑셀로 데이터를 주면서 배치작업을 요청 하는 경우가 있더라.. 뭐.. 텍스트 파일로 옮긴 후 처리를 하곤 했지만.. 내가 계속 해주기 귀찮더라이거지.. 그래서 아싸리. UI 프로그램을 하나 주면 편할 듯 싶어서 작업을 하게 됨.

Example
private JFileChooser fileChooser = new JFileChooser();

fileChooser.setDialogTitle("Excel Load");
fileChooser.setFileFilter(new TypeOfFile());

TypeOfFile
- 요넘.. 어딘가에서 가져왔지만. 까먹음.. 흠...
import java.io.File;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @author 0216
 */
public class TypeOfFile extends FileFilter {
     //Type of file that should be display in JFileChooser will be set here
     //We choose to display only directory and text file
     public boolean accept(File f)
     {
        return f.isDirectory()||f.getName().toLowerCase().endsWith(".xlsx");
     }

     //Set description for the type of file that should be display
     public String getDescription()
     {
        return ".xlsx";
     }
}

Posted by 짱가쟁이
우선은 이놈의 회사는 출근부에 도장을 찍듯이 인트라넷에 로그인을 해야 출근으로 인정되더라.. 좀 귀찮고 해서 그냥 일배치로 돌려볼 요량으로 찾게 되었음. (commons-httpclient-3.1.jar 사용)

뭐.. Post, Get 메소드를 제공하고 입맛에 맞게 잘 사용하면 되지만.. 결론은 인트라넷.. 잘 막아 놓았다는거.. 로그인 OK 페이지로 넘어가는 파라메터만 가지고는 좀 부족했는듯.. 좋은 방법이 없을까 ?? 쩌ㅃ~

Get Mehtod 사용법
HttpClient httpclient = new HttpClient();
GetMethod getPage1 = new GetMethod("http://bbaeggar.tistory.com");           
httpclient.executeMethod(getPage1);           
System.out.println(getPage1.getResponseBodyAsString());

Post Method 사용법도 별 어려움은 없는 듯..
Posted by 짱가쟁이
base64 인코딩된 데이터를 바이트로 디코딩후 이미지로 변환할 때 사용함.

Code
/**
     * byte array to image
     *
     * @param path      이미지 경로
     * @param buffer    이미지 데이터
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void byte2Image(String path, byte[] buffer) throws FileNotFoundException, IOException {
        FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
        imageOutput.write(buffer, 0, buffer.length);
        imageOutput.close();
    }

'java > util' 카테고리의 다른 글

[java] - File readLine  (2) 2010.07.01
[java] - File read  (0) 2010.07.01
[java] - 소수점 자르기 (duble type)  (0) 2010.06.30
[java] - base54 String decode  (0) 2010.06.30
[java] - 타입 변환  (0) 2010.06.30
Posted by 짱가쟁이
가끔 실수형을 계산하면 터무니 없이 길게 나오거나.. 몇번째 자리부터 근사값을 구하고 싶을 때 사용하면 됨.

code
/**
    * 적당한 길이로 자른다.
    *
    * @param size   
    * @param value
    * @return
    */
   public static String longDouble2String(int size, double value) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(size);
        nf.setGroupingUsed(false);
        return nf.format(value);
    }

Test
System.out.println(StringUtil.longDouble2String(2, 12.123456789));

Result
12.12

'java > util' 카테고리의 다른 글

[java] - File read  (0) 2010.07.01
[java] - byte array to image  (0) 2010.06.30
[java] - base54 String decode  (0) 2010.06.30
[java] - 타입 변환  (0) 2010.06.30
[java] - 외부 프로그램 실행하기..  (0) 2010.06.29
Posted by 짱가쟁이
이전버튼 1 2 3 4 5 6 7 ··· 12 이전버튼