SpringBoot - 리눅스 환경 파일 인코딩

박찬규·2023년 7월 17일

GoodJobProject

목록 보기
9/9

프로젝트를 진행하면서 간단한 닉네임 랜덤 생성기를 만들었다.

텍스트 파일 1에 관형사 약 200개를,
텍스트 파일 2에 명사 단어 약 250개를 넣고 서버에서 해당 파일을 읽어와 랜덤으로 조합하는 방식으로 제작했다.

코드는 아래와 같다.

@Component
public class NicknameGenerator {

    public String getRandomNickname() {
        String[] determiners = readWordFromFile("static/determiners.txt");
        String[] words = readWordFromFile("static/words.txt");

        Random random = new Random();
        String determiner = determiners[random.nextInt(determiners.length)];
        String word = words[random.nextInt(words.length)];

        return determiner + word;
    }

    public String[] readWordFromFile(String fileName) {
        try {
            ClassPathResource classPathResource = new ClassPathResource(fileName);
            BufferedReader br = new BufferedReader(new InputStreamReader(classPathResource.getInputStream()));

            String line;

            if ((line = br.readLine()) != null) {
                return line.split(", ");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }
}

이렇게 설정하고 로컬서버에서 테스트 해 본 결과 정상적으로 동작했는데,
운영서버에서 실행하니 닉네임이 다 깨져서 나왔다.
로컬 서버는 윈도우를 쓰지만 운영 서버는 리눅스 환경이기 때문에 파일을 읽어올 때 인코딩 방식이 달라 생기는 문제였다.

리눅스 콘솔에서 명령어로 파일 인코딩 방식을 바꿔도 되지만 일일이 바꿔주는 건 귀찮기도 하고 코드 내에서 해결하고 싶었기 때문에 파일을 읽어올 때 명시적으로 인코딩 방식을 정해주기로 했다.

BufferedReader br = new BufferedReader(
	new InputStreamReader(classPathResource.getInputStream())
);

BufferedReader br = new BufferedReader(
	new InputStreamReader(classPathResource.getInputStream(), "utf-8")
);

인코딩 방식을 utf-8로 지정해줬더니 정상적으로 한글을 읽어올 수 있었다.


이런식으로 관형사 + 단어 조합의 랜덤 닉네임을 사용할 수 있다.
간단하게 만들어서 조합 가능한 경우의 수가 적은데, 더 많은 회원을 대상으로 제공하는 서비스라면 단어 갯수를 늘려주면 될 것 같다.

1개의 댓글

comment-user-thumbnail
2023년 7월 17일

저도 개발자인데 같이 교류 많이 해봐요 ㅎㅎ! 서로 화이팅합시다!

답글 달기