Home | 简体中文 | 繁体中文 | 杂文 | Search | ITEYE 博客 | OSChina 博客 | Facebook | Linkedin | 作品与服务 | Email

1.8. Util

1.8.1. *.properties

		
package netkiller.test;

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

public class PropertiesTest {

	public static void main(String[] args) {

		System.out.println("Working Directory = " + System.getProperty("user.dir"));

		Properties ps = new Properties();
		try {
			ps.load(new FileInputStream("netkiller.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(ps.getProperty("key"));
	}

}
		
		

1.8.1.1. propertyNames()

			
package cn.netkiller.properties;

import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;

public class PropertiesTest {

	public PropertiesTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties properties = new Properties();

		properties.put("K1", "V1");
		properties.put("K2", "V2");

		for (Entry<Object, Object> x : properties.entrySet()) {
			System.out.println(x.getKey() + " " + x.getValue());
		}
		
		Enumeration<?> e = properties.propertyNames();
		while (e.hasMoreElements()) {
			String key = (String) e.nextElement();
			String value = properties.getProperty(key);
			System.out.println(key + ": " + value);
		}
	}

}
			
			
			
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Properties;

public class MainClass {
  public static void main(String args[]) throws Exception {
    Properties p = new Properties();
    p.load(new FileInputStream("test.properties"));
    Enumeration e = p.propertyNames();

    for (; e.hasMoreElements();) {
      System.out.println(e.nextElement());

    }
  }
}			
			
			

1.8.1.2. keySet()

			
package cn.netkiller.properties;

import java.util.Properties;
import java.util.Set;

public class PropertiesTest {

	public PropertiesTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties properties = new Properties();

		properties.put("K1", "V1");
		properties.put("K2", "V2");

		Set<Object> states = properties.keySet();

		for (Object name : states)
			System.out.println("The value of " + name + " is " + properties.getProperty((String) name) + ".");
	}

}

			
			

1.8.1.3. entrySet()

			
package cn.netkiller.properties;

import java.util.Map.Entry;
import java.util.Properties;

public class PropertiesTest {

	public PropertiesTest() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties properties = new Properties();

		properties.put("K1", "V1");
		properties.put("K2", "V2");

		for (Entry<Object, Object> x : properties.entrySet()) {
			System.out.println(x.getKey() + " " + x.getValue());
		}
	}

}
			
			

1.8.1.4. 方法中返回 Properties

			
	@RequestMapping("/host")
	public Enumeration<Object> host() throws IOException {
		Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(String.format("/%s.properties", "host")));
		return properties.keys();
	}

	@RequestMapping("/mail")
	public Collection<Object> mail() throws IOException {
		Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(String.format("/%s.properties", "mail")));
		return properties.values();
	}
	@RequestMapping("/nameserver")
	public Set<Entry<Object, Object>> nameserver() throws IOException {
		Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(String.format("/%s.properties", "dns")));
		return properties.entrySet();
	}
	@RequestMapping("/dns")
	public Properties dns() throws IOException {
		Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(String.format("/%s.properties", "dns")));
		return properties;
	}	
			
			

1.8.1.5. 

			
			
			

1.8.1.6. getResourceAsStream()

			
Properties prop = new Properties();
prop.load(getServletContext().getResourceAsStream("/WEB-INF/resource/sample.properties"));
			
			
			
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("netkiller.properties"));
			
			

1.8.1.7. store

			
package cn.netkiller.config;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class Config {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties prop = new Properties();
		OutputStream output = null;

		try {

			output = new FileOutputStream("config.properties");

			// set the properties value
			prop.setProperty("host", "localhost");
			prop.setProperty("port", "8000");
			prop.setProperty("user", "neo");
			prop.setProperty("pass", "password");

			// save properties to project root folder
			prop.store(output, null);

		} catch (IOException io) {
			io.printStackTrace();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}

}
			
			

getProperty 取出key的值

			
package cn.netkiller.config;

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

public class LoadConfig {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Properties prop = new Properties();
		InputStream input = null;

		try {

			input = new FileInputStream("config.properties");

			// load a properties file
			prop.load(input);

			// get the property value and print it out
			System.out.println(prop.getProperty("host"));
			System.out.println(prop.getProperty("port"));
			System.out.println(prop.getProperty("user"));
			System.out.println(prop.getProperty("pass"));

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
			
			

循环打印所有 Properties 内容

			
package test;

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

public class Application {

	public static void main(String[] args) {
		Application app = new Application();
		app.config();

	}

	private void config() {
		Properties prop = new Properties();
		InputStream input = null;
		try {

			String filename = "config.properties";

			prop.load(new FileInputStream(filename));

			Enumeration<?> e = prop.propertyNames();
			while (e.hasMoreElements()) {
				String key = (String) e.nextElement();
				String value = prop.getProperty(key);
				System.out.println(key + ": " + value);
			}

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
			
			

1.8.2. Logging

		
import java.util.logging.*;
public class Main {
	public static void main(String[] args) {
		Logger log = Logger.getLogger("test"); 
        log.setLevel(Level.INFO); 
        log.info("--------------------------");
        log.info("Test");
        log.info("--------------------------");
        
	}
}
		
		

XML

		
import java.io.IOException;
import java.util.logging.*;

public class Main {
	public static void main(String[] args) {

		try {
			Logger log = Logger.getLogger("test");
			FileHandler fileHandler = new FileHandler("test.%g.log");
			fileHandler.setLevel(Level.INFO);
			log.addHandler(fileHandler);
			
			log.setLevel(Level.INFO);
			log.info("One");
			log.info("Two");
			log.info("Three");
			
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}		
		
		

XML 输出结果

		
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE log SYSTEM "logger.dtd">
<log>
<record>
  <date>2016-04-19T15:57:19</date>
  <millis>1461052639360</millis>
  <sequence>0</sequence>
  <logger>test</logger>
  <level>INFO</level>
  <class>Main</class>
  <method>main</method>
  <thread>1</thread>
  <message>One</message>
</record>
<record>
  <date>2016-04-19T15:57:19</date>
  <millis>1461052639394</millis>
  <sequence>1</sequence>
  <logger>test</logger>
  <level>INFO</level>
  <class>Main</class>
  <method>main</method>
  <thread>1</thread>
  <message>Two</message>
</record>
<record>
  <date>2016-04-19T15:57:19</date>
  <millis>1461052639395</millis>
  <sequence>2</sequence>
  <logger>test</logger>
  <level>INFO</level>
  <class>Main</class>
  <method>main</method>
  <thread>1</thread>
  <message>Three</message>
</record>
</log>
		
		

Formatter 日志格式化

		
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

class LogFormatter extends Formatter {
	@Override
	public String format(LogRecord record) {
		return String.format("%s %s\t%s\n", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) , record.getLevel(), record.getMessage());
	}
}

public class Main {
	public static void main(String[] args) {

		try {
			Logger log = Logger.getLogger("test");
			FileHandler fileHandler = new FileHandler("test.%g.log");
			fileHandler.setLevel(Level.INFO);
			log.addHandler(fileHandler);
			fileHandler.setFormatter(new LogFormatter());
			log.setLevel(Level.INFO);
			log.info("One");
			log.info("Two");
			log.info("Three");

		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}		
		
		

输出样式

		
2016-04-19 16:05:53.324 INFO	One
2016-04-19 16:05:53.352 INFO	Two
2016-04-19 16:05:53.353 INFO	Three		
		
		

1.8.2.1. console

控制台日志输入格式定义

		ConsoleHandler consoleHandler = new ConsoleHandler();
		consoleHandler.setLevel(Level.OFF);
		logger.addHandler(consoleHandler);			
			

禁止 Console 输出

logger.setUseParentHandlers(false);			
			

1.8.3. BASE64

		
package cn.netkiller.test;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Test {
	public static void main(String[] args) {
		final String text = "http://www.netkiller.cn/index.html";

		final String encoded = Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8));
		System.out.println(encoded);

		final String decoded = new String(Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
		System.out.println(decoded);
	}
}
		
		
comments powered by Disqus