Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何加载我的属性文件?_Java_Jakarta Ee_Properties_Websphere_Messages - Fatal编程技术网

Java 如何加载我的属性文件?

Java 如何加载我的属性文件?,java,jakarta-ee,properties,websphere,messages,Java,Jakarta Ee,Properties,Websphere,Messages,我正在使用websphere和Java EE,并收到以下错误消息: Exception reading propertiesfile in init java.lang.NullPointerException java.lang.NullPointerException at java.io.Reader.<init>(Reader.java(Inlined Compiled Code)) at java.io.InputStreamReader.<init&

我正在使用websphere和Java EE,并收到以下错误消息:

Exception reading propertiesfile in init java.lang.NullPointerException
java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java(Inlined Compiled Code))
    at java.io.InputStreamReader.<init>(InputStreamReader.java(Inlined Compiled Code))
    at java.util.Properties.load(Properties.java(Compiled Code))
    at se.prv.register.admin.util.MessageHandler.loadDictionary(MessageHandler.java:90)
    at se.prv.register.admin.util.MessageHandler.<clinit>(MessageHandler.java:15)
读取init java.lang.NullPointerException中的属性文件时发生异常
java.lang.NullPointerException
在java.io.Reader.(Reader.java(内联编译代码))
在java.io.InputStreamReader。(InputStreamReader.java(内联编译代码))
加载(Properties.java(编译代码))
位于se.prv.register.admin.util.MessageHandler.loadDictionary(MessageHandler.java:90)
位于se.prv.register.admin.util.MessageHandler.(MessageHandler.java:15)
这是我的密码

package se.prv.pandora.arendeprocess.util;

import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

public class MessageHandler extends AbstractTextHandler{
    private static Properties dictionary;
    private final static String dictionaryFileName="messages.properties";
    private final static String className="se.prv.pandora.arendeprocess.util.MessageHandler";
    private static Logger logger = Logger.getLogger(MessageHandler.class);

    static {
        loadDictionary();
    }

    public static void main(String[] args) {
        String str = getParameterizedMessageTest("TEST",new String[]{"PETER","GÖRAN"});
        System.out.println(str);
    }
    public static String getMessage(String key){
        return getMessage(key,true);
    }
    public static String getMessage(String key,boolean useReference){
        logger.debug("!!!! getMessage "+ key);
        if (key==null || key.length()==0){
            throw new RuntimeException("GetMessage without key");
        }
        if (dictionary==null){
            loadDictionary();
        }
        if (useReference){
            return getFullMessage(getMessage(dictionary,key));
        }
        else {
            //String str = getMessage(dictionary,key);
            //logger.debug(str);
            String str2 = getCoreMessage(getMessage(dictionary,key));
            //logger.debug(str2);
            return str2;
        }
    }
    public static String getFirstPartOfMessage(String key){
        if (key==null || key.length()==0){
            throw new RuntimeException("GetMessage without key");
        }
        if (dictionary==null){
            loadDictionary();
        }
        String msg = getMessage(dictionary,key);
        int pos = msg.indexOf('$');
        if (pos==-1){
            return msg;
        }
        else {
            return msg.substring(0,pos);
        }
    }
    public static String getLastPartOfMessage(String key){
        if (key==null || key.length()==0){
            throw new RuntimeException("GetMessage without key");
        }
        if (dictionary==null){
            loadDictionary();
        }
        String msg = getMessage(dictionary,key);
        int pos = msg.lastIndexOf('$');
        if (pos==-1){
            return msg;
        }
        else {
            return msg.substring(pos+1);
        }
    }
    public static String getParameterizedMessage(String key, String [] params){
        if (dictionary==null){
            loadDictionary();
        }
        return getParameterizedMessage(dictionary,key,params);
    }
    private static void loadDictionary(){       
        String fileName = getPropertiesPath()+dictionaryFileName;
        //String fileName = "se/prv/register/admin/dao/sql-map-config.xml";

        try {
            dictionary=new Properties();
            //InputStream fileInput =  Class.forName("se.prv.register.admin.util.MessageHandler").getClassLoader().getResourceAsStream(fileName);
            InputStream fileInput =  Class.forName(className).getClassLoader().getResourceAsStream(fileName);
            dictionary.load(fileInput);
            fileInput.close();
        }
        catch(Exception e) {
            System.err.println("Exception reading propertiesfile in init "+e);
            e.printStackTrace();
            dictionary=null;
        }
    }
    private static String getCoreMessage(String str){
        StringBuffer buff = new StringBuffer();
        boolean doCopy=true;
        for (int i=0;i<str.length();i++){
            if (str.charAt(i)=='$'){
                doCopy=!doCopy;
                continue;
            }
            if (doCopy){
                buff.append(str.charAt(i));
            }
        }
        return buff.toString();
    }
    private static String getFullMessage(String str){
        int pos = str.indexOf('$');
        if (pos==-1){
            return str;
        }
        StringBuffer buff = new StringBuffer(str);

        int originalLength = buff.length();
        for (int i=pos+1;i<buff.length();i++){
            if (buff.charAt(i)== '$'){
                String key = buff.substring(pos+1,i).trim();
                String msg = getMessage(dictionary,key);
                buff.replace(pos,i+1,msg);
                if (buff.length()!=originalLength){
                    i += (buff.length()-originalLength);
                    originalLength=buff.length();
                }
                pos = buff.indexOf("$",i+1);
                if (pos==-1){
                    break;
                }
                else {
                    i = pos+1;
                }
            }
        }
        return buff.toString();
    }
//  private static void loadDictionary(){       
//      loadDictionary(dictionary,dictionaryFileName,className);
//  }
}

package se.prv.register.admin.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

import se.prv.framework.general.PRVWebSphere;
import se.prv.framework.util.Strings;

public abstract class AbstractTextHandler {

        private static final String propertiesPath="//se//prv//register//properties//";
        protected static Logger logger = Logger.getLogger(AbstractTextHandler.class);

//      static {
//          loadProperties();
//      }
        protected static String getPropertiesPath(){
            return propertiesPath;
        }
        protected static String getMessage(Properties dictionary,String key){
            if (dictionary==null){
                return "ERROR";
            }
            String msg = dictionary.getProperty(key);
            //System.out.println("KEY="+key);
            if (msg==null){
                return "?!Meddelande " +key + " saknas!?";
            }
            return msg;
        }
        protected static String getParameterizedMessage(Properties dictionary,String key,String []params){
            if (dictionary==null){
                return "ERROR";
            }
            String msg = dictionary.getProperty(key);
            if (msg==null){
                return "?!Meddelande " +key + " saknas!?";
            }
            if (params==null){
                return msg;
            }
            StringBuffer buff = new StringBuffer(msg);
            for (int i=0;i<params.length;i++){
                String placeHolder = "<<"+(i+1)+">>";
                if (buff.indexOf(placeHolder)!=-1){
                    replace(buff,placeHolder,params[i]);
                }
                else {
                    remove(buff,placeHolder);
                }
            }
            return buff.toString();
        }
        public static String getParameterizedMessageTest(String key,String []params){
            String msg = "HEJ <<1>>!HUR MÅR DU? HEJ DÅ FRÅN <<2>>";
            if (msg==null){
                return "?!Meddelande saknas!?";
            }
            if (params==null){
                return msg;
            }
            StringBuffer buff = new StringBuffer(msg);
            for (int i=0;i<params.length;i++){
                String placeHolder = "<<"+(i+1)+">>";
                if (buff.indexOf(placeHolder)!=-1){
                    replace(buff,placeHolder,params[i]);
                }
                else {
                    remove(buff,placeHolder);
                }
            }
            return buff.toString();
        }
        private static void replace(StringBuffer buff,String placeHolder,String param){
            int pos = buff.indexOf(placeHolder);
            if (pos==-1){
                return;
            }
            buff.replace(pos,pos+placeHolder.length(),param);
        }
        private static void remove(StringBuffer buff,String placeHolder){
            int pos = buff.indexOf(placeHolder);
            if (pos==-1){
                return;
            }
            buff.replace(pos,pos+placeHolder.length(),placeHolder);
        }
        protected static void loadDictionary(Properties dictionary,String fileName,String className){       
            //String fileName = "se/prv/register/admin/dao/sql-map-config.xml";

            try {
                dictionary=new Properties();
                InputStream fileInput =  Class.forName("se.prv.register.admin.util.AbstractTextHandler").getClassLoader().getResourceAsStream(fileName);
                dictionary.load(fileInput);
                fileInput.close();
            }
            catch(Exception e) {
                logger.error("Exception reading propertiesfile in init "+e);
                e.printStackTrace();
                dictionary=null;
            }
        }
    }
包se.prv.pandora.arendProcess.util;
导入java.io.InputStream;
导入java.util.Properties;
导入org.apache.log4j.Logger;
公共类MessageHandler扩展了AbstractTextHandler{
私有静态属性字典;
私有最终静态字符串字典filename=“messages.properties”;
私有最终静态字符串className=“se.prv.pandora.arendProcess.util.MessageHandler”;
私有静态记录器=Logger.getLogger(MessageHandler.class);
静止的{
loadDictionary();
}
公共静态void main(字符串[]args){
String str=getParameterizedMessageTest(“TEST”,新字符串[]{“PETER”,“GÖRAN”});
系统输出打印项次(str);
}
公共静态字符串getMessage(字符串键){
返回getMessage(key,true);
}
公共静态字符串getMessage(字符串键,布尔用户引用){
logger.debug(“!!!!getMessage”+键);
if(key==null | | key.length()==0){
抛出新的RuntimeException(“GetMessage With key”);
}
if(dictionary==null){
loadDictionary();
}
if(用户引用){
返回getFullMessage(getMessage(字典,键));
}
否则{
//String str=getMessage(字典,键);
//logger.debug(str);
字符串str2=getCoreMessage(getMessage(字典,键));
//logger.debug(str2);
返回str2;
}
}
公共静态字符串getFirstPartOfMessage(字符串键){
if(key==null | | key.length()==0){
抛出新的RuntimeException(“GetMessage With key”);
}
if(dictionary==null){
loadDictionary();
}
字符串msg=getMessage(字典,键);
int pos=msg.indexOf(“$”);
如果(位置==-1){
返回味精;
}
否则{
返回消息子串(0,位置);
}
}
公共静态字符串getLastPartOfMessage(字符串键){
if(key==null | | key.length()==0){
抛出新的RuntimeException(“GetMessage With key”);
}
if(dictionary==null){
loadDictionary();
}
字符串msg=getMessage(字典,键);
int pos=msg.lastIndexOf(“$”);
如果(位置==-1){
返回味精;
}
否则{
返回消息子串(位置+1);
}
}
公共静态字符串GetParameterizeMessage(字符串键,字符串[]参数){
if(dictionary==null){
loadDictionary();
}
返回getParameterizedMessage(字典、键、参数);
}
私有静态void loadDictionary(){
字符串文件名=getPropertiesPath()+字典文件名;
//String fileName=“se/prv/register/admin/dao/sql-map-config.xml”;
试一试{
dictionary=新属性();
//InputStream fileInput=Class.forName(“se.prv.register.admin.util.MessageHandler”).getClassLoader().getResourceAsStream(文件名);
InputStream fileInput=Class.forName(className).getClassLoader().getResourceAsStream(文件名);
加载(fileInput);
fileInput.close();
}
捕获(例外e){
System.err.println(“异常读取init中的属性文件”+e);
e、 printStackTrace();
dictionary=null;
}
}
私有静态字符串getCoreMessage(字符串str){
StringBuffer buff=新的StringBuffer();
布尔值doCopy=true;

对于(int i=0;i您应该将属性文件作为类路径资源而不是文件系统中的文件加载。请阅读本文,了解如何加载属性文件。

您应该将属性文件作为类路径资源而不是文件系统中的文件加载。请阅读本文,了解如何加载属性文件。

不要执行以下操作

InputStream fileInput = Class.forName(className).getClassLoader().getResourceAsStream(fileName);
这样做:

InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);

而不是做下面的事情

InputStream fileInput = Class.forName(className).getClassLoader().getResourceAsStream(fileName);
这样做:

InputStream fileInput = MessageHandler.class.getClassLoader().getResourceAsStream(fileName);
线路
InputStream fileInput=Class.forName(className).getClassLoader().getResourceAsStream(fileName);

返回
null

这就是NPE被扔进阅读器的原因

问题是为什么输入流为空?因为
文件名
包含错误的值。所以,调试它。在第行中切换断点

String fileName=getPropertiesPath()+dictionaryFileName;

看看它会返回什么。

InputStream fileInput=Class.forName(className).getClassLoader().getResourceAsStream(fileName);

返回
null

这就是NPE被扔进阅读器的原因

问题是为什么输入流为空?因为
文件名
包含错误的值。所以,调试它。在第行中切换断点

String fileName=getPropertiesPath()+dictionaryFileName;


查看返回的内容。

您看到的异常是从
属性.load()的深度引发的空指针异常。原因是传递的参数(
fileInput
)为空。很可能是因为
fileName
中指定的路径不正确

请尝试使用
/
预先设置路径

另外,请确保该文件存在。
getResourceAsStream()
方法将在与该类关联的资源中查找该文件(例如,如果运行程序,它必须是.jar的一部分)