Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 | 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

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!");
	}

}