多语言包

类别:Java 点击:0 评论:0 推荐:

多语包使用的方法看Resource的注释即可,所有的功能都在Resource中定义了。

在XMLResource类中有Main方法,可以直接运行。

在调用之前先执行XMLResource.import方法把文件调入。

软件使到了一个资源文件为XML文件,格式如最后所示。

以下文件编译即可运行

=======================Resource.java =======================

package org.fswan;

 

import java.util.Locale;

import java.util.Properties;

 

/**

 * @author Swan Fong(方志文)

 * e-mail:[email protected]

 * 用来读资源文件用的接口,跟不同语言获取不同的字符串

 * 如果在获取资源的同传入的地区代码为NULL的话则使用缺省的地区代码

 */

public interface Resource {

    /**

     * 获取跟名称相对应的资源的内容

     * @param name 名称

     * @param locale 语言

     * @return 资源内容

     */

    public String getResource(String name,Locale locale);

    /**

     * 获取带有参数的资源的内容

     * @param name 资源的名称

     * @param property 资源的参数值

     * @param locale 语言

     * @return 资的内容

     */

    public String getResource(String name,String[] property,Locale locale);

    /**

     * 获取一组资源

     * 如果目录名为common.title,是把处于common下title下的所有的所有的资源显示出来

     * property是参数名,对应category下资源的长度,第二维为长度。如果长度小于category的长度

     * 则把最后一个作为这之后的所有的资源的参数,如果为null则所有的资源都没参数。

     * @param category 目录名

     * @param property 参数

     * @param locale 语言

     * @return 资源数组

     */

    public Properties getResource(String category,String[][] property,Locale locale);

    /**

     * 获取目录下所有的资源的名

     * @param category 目录名

     * @param locale 语言

     * @return 所有的子项的数组

     */

    public String[] getResourceNames(String category,Locale locale);

    /**

     * 获取目录下所有的资源或子目录

     * @param category 目录名

     * @param isCategory 返回的是子目录还是资源

     * @param locale 语言

     * @return 返回的内容

     */

    public String[] getResourceNames(String category,boolean isCategory,Locale locale);

}

 

 

===============End ================================

==============XMLResource.java======================

package org.fswan;

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Hashtable;

import java.util.Locale;

import java.util.Properties;

import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.FactoryConfigurationError;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

/**

 * @author Swan Fong(方志文)

 * E-mail:[email protected]

 * 从XML文件获取资源的类

 * 资源的定位方式为树形层之间用逗号隔开。

 * 如资源文件内容为以下内空

 * <resource>

 * <form1><title1>Title1</title1><title2>Title2</title2>

 * </form1>

 * </resource>

 * 则获取资源form1.title1的内容为Title1

 * 获取资源form1的内容为title1和title2

 *

 * 也可以使用%1来替换,比如 Title of %1

 * 在调用时使用getResource("xxxx","Book")时会变成 Title of Book

 *

 */

public class XmlResource implements Resource

{

    /**

     * 用来存放资源,Hashtable的Key是Locale型,值是Element型的,对应不同的Locale有不同的Document

     */

    private static Hashtable resources;

    /**

     * 缺省的语言

     */

    private static Locale defaultLocale = new Locale("zh", "CN");

    static {

        ArrayList list = ResourceLib.getXmlResource();

       for (int i = 0; i < list.size(); i++)

       {

           importXML(list.get(i).toString());

       }

    }

    public static void importXML(String fileName)

    {

       try

       {

           DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();

           DocumentBuilder builder = builderFac.newDocumentBuilder();

           Document doc = null;

 

           if(new File(fileName).exists())

           doc = builder.parse(new File(fileName));

           else

           doc = builder.parse(XmlResource.class.getResourceAsStream(fileName));

           Element root = doc.getDocumentElement();

           NodeList nl = root.getElementsByTagName("resource");

           resources = new Hashtable();

           for (int i = 0; i < nl.getLength(); i++)

           {

               Element el = (Element) nl.item(i);

               Locale locale = new Locale(el.getAttribute("language"), el.getAttribute("country"));

               resources.put(locale, el);

           }

       } catch (FactoryConfigurationError e)

       {

           e.printStackTrace();

       } catch (ParserConfigurationException e)

       {

           e.printStackTrace();

       } catch (SAXException e)

       {

           e.printStackTrace();

       } catch (IOException e)

       {

           e.printStackTrace();

       }

    }

    /* (non-Javadoc)

     * @see org.fswan.db.Resource#getResource(java.lang.String, java.util.Locale)

     */

    public String getResource(String name, Locale locale)

    {

       if (locale == null)

           locale = defaultLocale;

        Element el = null;

        if(resources.get(locale)!=null)

       el = (Element) resources.get(locale);

       else

       el = (Element) resources.get(defaultLocale);

      

        StringTokenizer stk = new StringTokenizer(name, ".");

       while (stk.hasMoreTokens())

       {

           NodeList nl = el.getElementsByTagName(stk.nextToken());

           if (nl.getLength() < 1)

               return null;

           el = (Element) nl.item(0);

       }

        return el.getChildNodes().item(0).getNodeValue();

    }

    /* (non-Javadoc)

     * @see org.fswan.db.Resource#getResource(java.lang.String, java.lang.String[], java.util.Locale)

     */

    public String getResource(String name, String[] property, Locale locale)

    {

       if (property == null || property.length == 0)

           property = new String[] { "" };

        String tmpStr = getResource(name, locale);

        StringBuffer sb = new StringBuffer(tmpStr);

       int i = 1;

       int pos = getPosition(sb, i);

       while (pos != -1)

       {

           sb.replace(

               pos,

               pos + ("%" + i).length(),

               property[(i - 1 > property.length) ? property.length - 1 : i - 1]);

           i++;

           pos = getPosition(sb, i);

       }

        return sb.toString();

    }

    /**

     * 获取StringBuffer中出现%i的位置,如果前面是\的话则不算,如果找不到则返回-1

     * @param str 要查找的字符串

     * @param i 要查找的内容

     * @return 位置

     */

    private int getPosition(StringBuffer str, int i)

    {

       int pos = str.indexOf("%" + i);

       while (pos != -1 && str.charAt(pos - 1) == '\\')

       {

           pos = str.indexOf("%" + i, pos);

       }

        return pos;

    }

    /* (non-Javadoc)

     * @see org.fswan.db.Resource#getResource(java.lang.String, java.lang.String[][], java.util.Locale)

     */

    public Properties getResource(String category, String[][] property, Locale locale)

    {

       if (property == null || property.length == 0)

       {

           property = new String[1][1];

           property[0][0] = "";

       }

        String[] names = getResourceNames(category, false, locale);

        String[] values = new String[names.length];

        Properties p = new Properties();

       for (int i = 0; i < values.length; i++)

       {

           String[] pro = property[(i > property.length - 1) ? property.length - 1 : i];

          values[i] = getResource(category + "." + names[i], pro, locale);

           p.setProperty(names[i], values[i]);

       }

        return p;

    }

    /* (non-Javadoc)

     * @see org.fswan.db.Resource#getResourceNames(java.lang.String, boolean, java.util.Locale)

     */

    public String[] getResourceNames(String category, boolean isCategory, Locale locale)

    {

       if (locale == null)

           locale = defaultLocale;

        Element el = null;

        if(resources.get(locale)!=null)

       el = (Element) resources.get(locale);

       else

       el = (Element) resources.get(defaultLocale);

 

        StringTokenizer stk = new StringTokenizer(category, ".");

       while (stk.hasMoreTokens())

       {

           NodeList nl = el.getElementsByTagName(stk.nextToken());

           if (nl.getLength() < 1)

               return null;

           el = (Element) nl.item(0);

       }

        NodeList nl = el.getElementsByTagName("*");

       if (nl == null || nl.getLength() == 0)

           return new String[] {

       };

        String[] resources = new String[nl.getLength()];

       for (int i = 0; i < nl.getLength(); i++)

       {

           resources[i] = nl.item(i).getNodeName();

       }

        return resources;

    }

    /* (non-Javadoc)

     * @see org.fswan.db.Resource#getResourceNames(java.lang.String, java.util.Locale)

     */

    public String[] getResourceNames(String category, Locale locale)

    {

       if (locale == null)

           locale = defaultLocale;

        Element el = null;

        if(resources.get(locale)!=null)

       el = (Element) resources.get(locale);

       else

       el = (Element) resources.get(defaultLocale);

        StringTokenizer stk = new StringTokenizer(category, ".");

       while (stk.hasMoreTokens())

       {

           NodeList nl = el.getElementsByTagName(stk.nextToken());

           if (nl.getLength() < 1)

               return null;

           el = (Element) nl.item(0);

       }

        NodeList nl = el.getElementsByTagName("*");

       if (nl == null || nl.getLength() == 0)

           return new String[] {

       };

        String[] resources = new String[nl.getLength()];

       for (int i = 0; i < nl.getLength(); i++)

       {

           resources[i] = nl.item(i).getNodeName();

       }

        return resources;

    }

    public static void main(String[] args)

    {

        XmlResource.importXML("com/fswan/application/AddressBook/resource.xml");

        Properties first = new XmlResource().getResource("addressbook", (String[][]) null, null);

        Object[] s = first.keySet().toArray();

       for (int i = 0; i < s.length; i++)

       {

           System.out.println(s[i] + "  " + first.getProperty(s[i].toString()));

       }

    }

}

 

==========================END=================================

==========================XML文件的格式=========================

<?xml version="1.0" encoding="UTF-8"?>

<!-- edited with XMLSPY v2004 rel. 3 U (http://www.xmlspy.com) by fswan (fswan) -->

<root>

   <resource language="en">

      <mainframe>

          <title>Human Resource Management System</title>

          <menu>

             <file>File</file>

             <new>New</new>

             <save>Save</save>

             <load>Load</load>

             <saveas>Save as...</saveas>

             <edit>Edit</edit>

             <copy>Copy</copy>

             <parse>Parse</parse>

             <delete>Delete</delete>

             <nextpage>Next Page</nextpage>

             <tool>Tool</tool>

             <language>Language</language>

             <default>Default</default>

             <english>English</english>

             <china>Simplified</china>

             <tchina>Tradition</tchina>

             <employee>Employee Management</employee>

             <detail>Detail</detail>

             <employeelist>Employee List</employeelist>

             <lookandfeel>Look and Feel</lookandfeel>

             <javalook>Java Look</javalook>

             <motiflook>Motif Look</motiflook>

             <windowlook>Window Look</windowlook>

             <defaultlook>Default</defaultlook>

             <emeraldlook>Emerald</emeraldlook>

             <sapphire>Sapphire</sapphire>

          </menu>

      </mainframe>

   </resource>

   <resource language="zh" country="CN">

      <mainframe>

          <title>人力资源管理系统</title>

          <menu>

             <file>文档</file>

             <new>新建</new>

             <save>储存</save>

             <load>存盘</load>

             <saveas>另存为</saveas>

             <edit>编辑</edit>

             <copy>拷贝</copy>

             <parse>粘贴</parse>

             <delete>删除</delete>

             <nextpage>下页</nextpage>

             <tool>工具</tool>

             <language>语言</language>

             <default>缺省</default>

             <china>中文</china>

             <tchina>繁体中文</tchina>

             <english>英文</english>

             <employee>员工管理</employee>

             <detail>员工资料</detail>

             <employeelist>员工列表</employeelist>

             <lookandfeel>外观</lookandfeel>

             <javalook>Java 外观</javalook>

             <motiflook>Motif 外观</motiflook>

             <windowlook>Windows 外观</windowlook>

             <defaultlook>默认</defaultlook>

             <emeraldlook>祖母绿</emeraldlook>

             <sapphire>海蓝宝石</sapphire>

          </menu>

      </mainframe>

   </resource>

</root>

=========================END===================================

 

 

本文地址:http://com.8s8s.com/it/it14071.htm