자바

MessageFormat

devjones 2020. 11. 15. 16:38

MessageFormat은 다수의 데이터를 같은 양식으로 출력할 때 주로 사용한다.

또한 parse메소드를 이용하여 지정된 양식(pattern)으로부터 데이터를 추출할 수도 있다.

 

package messageFormatSample;

import java.text.MessageFormat;

public class Main01 {

	public static void main(String[] args) {
		
		String pttrn = "첫번째 : {0} \n두번째 : {1} \n세번째 : {2} \n네번째  : {3}";
		Object[] arguments = {"가나다", "ABC", "123", "!@#"};
		
		String result = MessageFormat.format(pttrn, arguments);
		System.out.println(result);
	}
}

 

 

예제에서는 모두 String을 사용하였지만 데이터의 배열은 객체형태이므로 int, double, char, boolean 등 다양한 형태로의 값을 입력할 수 있다.

 

아래 예제를 통해 조금 더 발전된 MessageFormat 형태를 사용해보자.

package messageFormatSample;

import java.text.MessageFormat;

public class Main03 {

	public static void main(String[] args) {
		
		// From Objects to Strings
		String pattern ="VALUES (\"{0}\",''{1}'',{2},''{3}'')";
        Object[][] argument = {{"이자바", "29세", "경기도", "학생"}, {"김프로", "34세", "서울", "직장인"}};
        
        String[] result = new String[2];
        
        for(int i = 0; i < argument.length; i++) {
        	result[i] = MessageFormat.format(pattern, argument);
        	System.out.println(result[i]);
        }
        
        // From Strings to Objects
        MessageFormat mf = new MessageFormat(pattern);
        Object[][] lastResult;
        
        try {
            for(int i = 0; i < result.length; i++) {
                Object[] obj = mf.parse(result[i]);
                for(int j = 0; j < obj.length; j++) {
                    lastResult = new String[result.length][obj.length];
                    lastResult[i][j] = (String) obj[j];   // 다시 2차원 배열로 반환
                    System.out.print("obj["+i+"]["+j+"] : " +lastResult[i][j]);
 
                    if(j != obj.length-1)
                        System.out.print(", ");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}

d람ㄴfasfaskfjaskldfjaslfasdflㄹㅇ날낭러나이런일

asdfkajsldifjasldfjaklsdfalsfdlkasjdfklasfd

위의 예제에서 보면 String에서 Object배열로 파싱할 때 try/catch문으로 감쌋는데 이는 지정된 pattern과 파싱할 데이터의 형태가 다르면 ParseException이 발생하기 때문에 예외처리를 해주어야 한다.

 

위의 예제는 입력값을 변경하려면 코드를 수정해야 하므로 불편함이 있다.

때문에 실제 사용에서는 외부 파일을 읽어들여 데이터를 출력하는 형식으로 사용한다.

간단한 예제로 파일을 Scanner로 읽어들여 형식화하는 코드를 살펴보자.

 

package messageFormatSample;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.Scanner;

public class Main04 {
	public static void main(String[] args) {
		 
        /* test.txt 파일내용 (해당 클래스와 같은 패키지 않에 존재함) 
        name: 이자바, number: 02-123-1234, birth: 07-09    
        name: 김프로, number: 031-112-2345, birth: 10-07
        */ 
 
        // 같은 패키지 않에 있으므로 해당클래스의 '절대경로'를 얻어옴
        String path = Main04.class.getResource("").getPath();
    
        // 절대경로 + 파일명
        String fileName = path +"test.txt";
        String pattern = "name: {0}, number: {1}, birth: {2}";
 
        Scanner s = null;
        // 파일이 존재하지 않을 경우를 위에 예외처리
        try {
            s = new Scanner(new File(fileName));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
 
        MessageFormat mf = new MessageFormat(pattern);
 
        while(s.hasNextLine()) {
            String line = s.nextLine();
            Object[] objs = null;
            
            try { 
                objs = mf.parse(line);
            } catch (ParseException e) {
            e.printStackTrace();
            }
 
            System.out.println(MessageFormat.format(pattern, objs));
        }
        s.close();  // 작업이 끝나면 Scanner는 항상 닫아준다
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

출처:

bbiyakbbiyak.tistory.com/14