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 짱가쟁이