---
title: "Eclipse  国际化"
author: "Irving_wei"
date: "2012-12-17T17:31:32Z"
tags: []
categories: ["开源软件"]
slug: "eclipse"
draft: false
lastmod: "2012-12-17T17:36:22Z"
id: 1749166
url: "https://irving-wei.iteye.com/blog/1749166"
---

Eclipse 提供了方便的国际化实现方式。

 

例子：

新建项目 i18n 

package test;

 

public class I18NTest { 

    public I18NTest() {

       String testString = "Hello ,I18N!";

       System.out.println(testString);

    }

  

    public static void main(String\[] args) {

        new I18NTest() ;

    }

}

 

在导航器里面右击该类，Source---&gt;Externalize Strings... 

 

 ![](http://dl.iteye.com/upload/attachment/0078/0499/26a25054-d26c-3c12-b943-543e7994b31d.png)

&lt;!--EndFragment--&gt;

 

一直“下一步”，最后，会生成出这两个文件![](http://dl.iteye.com/upload/attachment/0078/0501/7454e1f2-a14a-3a09-80cb-bab29cbffdec.png)，而I18NTest这个类也改变了：

package test;

 

public class I18NTest {

    

    public I18NTest() {

       String testString = Messages.getString("I18NString.hello"); //$NON-NLS-1$

       System.out.println(testString);

    }

  

    public static void main(String\[] args) {

        new I18NTest() ;

    }

 

}

 

//$NON-NLS-1$ 这个注释是eclipse自己用的，最后的数字 1 表示该行的第几个数字是不用国际化的。

这个类的国际化就这样完成了。

想要这个类随着不同的语言环境得到不同的输出结果，可以在messages.properties的相同目录下建立message\_区域代码.properties

在eclipse的运行设置里面添加-nl zh\_cn 类似这样的信息，就可以调试不同地区的显示结果。

如果资源文件有多个参数，如：

I18NTest.TestString=My name is  {0} ,today is {1} ,date is {2} .

 

程序可以改为：

package test;

 

import java.text.MessageFormat;

import java.util.Date;

 

public class I18NTest {

 

    static String testString = Messages.getString("I18NTest.TestString"); //$NON-NLS-1$

 

    public static void main(String\[] args) {

        String name = "Irving"; //$NON-NLS-1$

        String today = "Monday"; //$NON-NLS-1$

        Date date = new Date();

 

        String result = MessageFormat.format(testString, new Object\[] { name, today, date });

        System.out.println(result);

    }

}

 

 

如果想格式化时间，只需要修改资源文件为：

 

I18NTest.TestString=My name is  {0} ,today is {1} ,date is {2,date,yyyy-MM-dd}  .

注意，2之后不能有空格。