Home | 简体中文 | 繁体中文 | 杂文 | 知乎专栏 | 51CTO学院 | CSDN程序员研修院 | Github | OSChina 博客 | 腾讯云社区 | 阿里云栖社区 | Facebook | Linkedin | 打赏(Donations) | About
知乎专栏多维度架构

1.12. Util

1.12.1. Properties 处理 *.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.12.1.1. 打开 properties 文件

1.12.1.1.1. 文件方式打开
				
BufferedReader br = null;
Properties properties = new Properties();
br = new BufferedReader(new InputStreamReader(new  FileInputStream(new File("data.properties")), "UTF8"));
properties.load(br);				
				
				
1.12.1.1.2. 输入流
				
Properties properties = new Properties();
InputStream in = getClass().getResourceAsStream("/IcisReport.properties");
properties.load(in);
Set keyValue = properties.keySet();
for (Iterator it = keyValue.iterator(); it.hasNext();)
{
	String key = (String) it.next();
}				
				
				

1.12.1.2. 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.12.1.3. 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.12.1.4. 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.12.1.5. 方法中返回 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.12.1.6. 

			
			
			

1.12.1.7. getResourceAsStream()

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

1.12.1.8. 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.12.1.9. 实现国际化

准备语言包文件 chinese.properties 内容如下

			
hello=你好世界
			
			

english.properties

			
hello=Helloworld
			
			
			 
	@GetMapping("/lang")
	public String lang(@RequestHeader String lang) throws IOException {
		System.out.println(lang);
		Properties properties = PropertiesLoaderUtils.loadProperties(new ClassPathResource(lang + ".properties"));
		String tmp = properties.getProperty("hello");
		return tmp;
	}
			 
			

测试效果

			
curl -s -H lang:chinese http://localhost:8080/lang
你好世界

curl -s -H lang:english http://localhost:8080/lang
Helloworld
			
			

1.12.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.12.2.1. console

控制台日志输入格式定义

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

禁止 Console 输出

				logger.setUseParentHandlers(false);
			

1.12.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);
	}
}
		
		

1.12.4. Locale 国际化

		
package cn.netkiller.i18n;

import java.util.Locale;

public class Lang {

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

	public static void main(String[] args) {
		// create a new locale
		Locale locale = new Locale("ENGLISH", "US");

		// print locale
		System.out.println("Locale:" + locale);

		// print display name for locale - based on inLocale
		System.out.println("Name:" + locale.getDisplayName(new Locale("GERMAN", "GERMANY")));

	}

}
		
		
		
Locale locale = new Locale("zh", "CN");
Locale locale = Locale.US;
Locale locale = Locale.getDefault();	// 默认语言	
		
		

1.12.5. ResourceBundle

		
java.util.ResourceBundle resourceBundle = java.util.ResourceBundle.getBundle("message");

resourceBundle.getString("nickname");	

// 指定语言

Locale  locale = new Locale("zh", "CN");
ResourceBundle res = ResourceBundle.getBundle("message", locale);	
		
		

1.12.6. Scanner

		
Scanner in = new Scanner(System.in);
System.out.println("Username:");
String username = in.next();
      		
		
		

1.12.7. UUID

		
package cn.netkiller.example.uuid;

import java.util.UUID;

public class UuidTest {

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

	public static void main(String[] args) {
		UUID uuid = UUID.randomUUID();
		String randomUUIDString = uuid.toString();

		System.out.println("Random UUID String = " + randomUUIDString);
		System.out.println("UUID version       = " + uuid.version());
		System.out.println("UUID variant       = " + uuid.variant());
	}

}
		
		
		

1.12.8. Arrays.equals 判断两个数组是否相等

static boolean equals(type[] a, type[] b)

		
Arrays.equals(array1, array2)		
		
		

1.12.9. Random 随机字符串

		
package cn.netkiller.test;

import java.util.Random;

public class QueueTest {

	public static void main(String[] args) throws InterruptedException {
		new Random().ints(10, 33, 38).forEach(System.out::println);
	}
}
		
		
		
		
36
34
34
36
37
35
34
35
34
33
		
		
		

1.12.9.1. 指定随机数范围

			
package cn.netkiller.test;

import java.util.Random;

public class RandomTest {

	public static int random(int min, int max) {
		var value = new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();
		return value;
	}

	public static void main(String[] args) throws InterruptedException {
		System.out.println(random(10, 15));
	}
}
			
			
			

1.12.10. ArrayBlockingQueue

		
package cn.netkiller.test;

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class QueueTest {
	/**
	 * 定义装苹果的篮子
	 */
	public static class Basket {
		// 篮子,能够容纳10个苹果
		BlockingQueue<String> basket = new ArrayBlockingQueue<String>(10);

		// 生产苹果,放入篮子
		public void produce() throws InterruptedException {
			// put方法放入一个苹果,若basket满了,等到basket有位置
			basket.put("An apple");
		}

		// 消费苹果,从篮子中取走
		public String consume() throws InterruptedException {
			// get方法取出一个苹果,若basket为空,等到basket有苹果为止
			return basket.take();
		}

		public int size() {
			return basket.size();
		}

	}

	// 测试方法
	public static void testBasket() throws InterruptedException {
		// 建立一个装苹果的篮子
		final Basket basket = new Basket();
		// 定义苹果生产者
		class Producer implements Runnable {
			public void run() {
				try {
					while (true) {
						int n = random(1, 5);
						for (int i = 0; i < n; i++) {
							basket.produce();
						}
						System.out.println(System.currentTimeMillis() + " 放入" + n + "个,当前总数:" + basket.size() + "个");
						Thread.sleep(random(450, 1000));
					}
				} catch (InterruptedException ex) {
				}
			}
		}
		// 定义苹果消费者
		class Consumer implements Runnable {
			public void run() {
				try {
					while (true) {
						// 消费苹果
						int n = random(1, 5);
						for (int i = 0; i < n; i++) {
							basket.consume();
						}
						System.out.println(System.currentTimeMillis() + " 取出" + n + "个,剩余数量:" + basket.size() + "个");
						Thread.sleep(random(400, 1000));
					}
				} catch (InterruptedException ex) {
				}
			}
		}

		ExecutorService service = Executors.newCachedThreadPool();
		Producer producer = new Producer();
		Consumer consumer = new Consumer();
		service.submit(producer);
		// 延迟消费
		Thread.sleep(5000);
		service.submit(consumer);
		// 程序运行10s后,所有任务停止
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
		}
		service.shutdownNow();
	}

	public static int random(int min, int max) {
		var value = new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();
		return value;
	}

	public static void main(String[] args) throws InterruptedException {
		QueueTest.testBasket();
	}
}

		
		

1.12.11. CRC32

		
package cn.netkiller.security;

import java.nio.ByteBuffer;
import java.util.zip.CRC32;

public class CRC {

	public static void main(String[] args) {

		final CRC32 crc32 = new CRC32();
		ByteBuffer data = ByteBuffer.wrap("http://www.netkiller.cn".getBytes());
		crc32.update(data);
		System.out.println(crc32.getValue());

	}

}		
		
		

1.12.12. FutureTask

	
package cn.netkiller.welcome;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Future {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		// TODO Auto-generated method stub
		FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				String status = null;
				System.out.println(Thread.currentThread().getName() + ":" + "Send SMS ...");
				Thread.sleep(2000);
				System.out.println(Thread.currentThread().getName() + ":" + "Sent");
				status = "OK";
				return status;
			}
		});

//		开启了一个线程执行future的逻辑
		Thread thread = new Thread(futureTask);
		thread.start();

		// 主业务逻辑
		System.out.println(Thread.currentThread().getName() + ":" + "Begin");
		Thread.sleep(3000);
		System.out.println(Thread.currentThread().getName() + ":" + "End");

		String sent = futureTask.get();

		System.out.println(Thread.currentThread().getName() + ":" + "Status:" + sent + " done!");
	}

}