java中Properties配置文件中「\r\n」和「\n」的影響

首先加載Properties文件的方式有兩種:java

一種是經過spring框架加載:

<context:property-placeholder location="classpath*:server.properties" ignore-unresolvable="true" />

咱們經過源碼來分析spring解析Properties文件是由PropertiesLoaderUtils類的fillProperties方法來解析的,源碼以下spring

/**
	 * Actually load properties from the given EncodedResource into the given Properties instance.
	 * @param props the Properties instance to load into
	 * @param resource the resource to load from
	 * @param persister the PropertiesPersister to use
	 * @throws IOException in case of I/O errors
	 */
	static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister)
			throws IOException {

		InputStream stream = null;
		Reader reader = null;
		try {
			String filename = resource.getResource().getFilename();
			if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) {
				stream = resource.getInputStream();
				persister.loadFromXml(props, stream);
			}
			else if (resource.requiresReader()) {
				reader = resource.getReader();
				persister.load(props, reader);   //關鍵方法
			}
			else {
				stream = resource.getInputStream();
				persister.load(props, stream);   //關鍵方法
			}
		}
		finally {
			if (stream != null) {
				stream.close();
			}
			if (reader != null) {
				reader.close();
			}
		}
	}

經過以上源碼咱們能夠發現PropertiesLoaderUtils類調用了PropertiesPersister的load方法,源碼以下框架

public class DefaultPropertiesPersister implements PropertiesPersister {

	@Override
	public void load(Properties props, InputStream is) throws IOException {
		props.load(is);
	}

	@Override
	public void load(Properties props, Reader reader) throws IOException {
		props.load(reader);
	}

......
}

而PropertiesPersister是經過Properties類來處理的,而Properties類則是java提供的,源碼以下ide

public class Properties extends Hashtable<Object,Object> {
    public synchronized void load(InputStream inStream) throws IOException {
        load0(new LineReader(inStream));
    }

    private void load0 (LineReader lr) throws IOException {
        char[] convtBuf = new char[1024];
        int limit;
        int keyLen;
        int valueStart;
        char c;
        boolean hasSep;
        boolean precedingBackslash;

        while ((limit = lr.readLine()) >= 0) {  //讀取一行信息
            c = 0;
            keyLen = 0;
            valueStart = limit;
            hasSep = false;
   ......

經過以上源碼能夠發現咱們須要關注的地方是lr.readLine()用了讀取一行信息,主要源碼以下工具

if (c != '\n' && c != '\r') {       //若是是"\n"或者"\r"則跳到else裏面,else裏是讀取一行信息結束
                    lineBuf[len++] = c;
                    if (len == lineBuf.length) {
                        int newLength = lineBuf.length * 2;
                        if (newLength < 0) {
                            newLength = Integer.MAX_VALUE;
                        }
                        char[] buf = new char[newLength];
                        System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
                        lineBuf = buf;
                    }
                    //flip the preceding backslash flag
                    if (c == '\\') {
                        precedingBackslash = !precedingBackslash;
                    } else {
                        precedingBackslash = false;
                    }
                }
                else {
                    // reached EOL
                    if (isCommentLine || len == 0) {
                        isCommentLine = false;
                        isNewLine = true;
                        skipWhiteSpace = true;
                        len = 0;
                        continue;
                    }
                    if (inOff >= inLimit) {
                        inLimit = (inStream==null)
                                  ?reader.read(inCharBuf)
                                  :inStream.read(inByteBuf);
                        inOff = 0;
                        if (inLimit <= 0) {
                            return len;
                        }
                    }

經過以上代碼能夠發現"\n"和"\r"都會認爲是一行的結束。ui

結論「\r\n」和「\n」對spring方式讀取Properties無影響

 

另外一種是不經過spring方式讀取

package com.hs.util;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Desc:properties文件獲取工具類
 * 
 */
public class PropertyUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
    private static Properties   props;
    static {
        loadProps();
    }

    synchronized static private void loadProps() {
        logger.info("開始加載properties文件內容.......");
        props = new Properties();
        InputStream in = null;
        try {
            in = PropertyUtil.class.getClassLoader()
                .getResourceAsStream("server.properties");
            
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error("properties文件未找到");
        } catch (IOException e) {
            logger.error("出現IOException");
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("properties文件流關閉出現異常");
            }
        }
        logger.info("加載properties文件內容完成...........");
        logger.info("properties文件內容:" + props);
    }

    public static String getProperty(String key) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if (null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}

經過以上代碼能夠發現,這種方式其實也是經過java提供的Properties類來加載的,因此「\r\n」和「\n」對讀取Properties文件沒有影響spa

相關文章
相關標籤/搜索