1.list转set
- Set set = new HashSet(new ArrayList());
2.set转list
- List list = new ArrayList(new HashSet());
3.数组转为list
- List stooges = Arrays.asList("Larry", "Moe", "Curly");
此时stooges中有有三个元素。注意:此时的list不能进行add操作,否则会报“java.lang.UnsupportedOperationException”,Arrays.asList()返回的是List,而且是一个定长的List,所以不能转换为ArrayList,只能转换为AbstractList
原因在于asList()方法返回的是某个数组的列表形式,返回的列表只是数组的另一个视图,而数组本身并没有消失,对列表的任何操作最终都反映在数组上. 所以不支持remove,add方法的
- String[] arr = {"1", "2"};
- List list = Arrays.asList(arr);
4.数组转为set
- int[] a = { 1, 2, 3 };
- Set set = new HashSet(Arrays.asList(a));
5.map的相关操作。
- Map map = new HashMap();
- map.put("1", "a");
- map.put('2', 'b');
- map.put('3', 'c');
- System.out.println(map);
- // 输出所有的值
- System.out.println(map.keySet());
- // 输出所有的键
- System.out.println(map.values());
- // 将map的值转化为List
- List list = new ArrayList(map.values());
- System.out.println(list);
- // 将map的值转化为Set
- Set set = new HashSet(map.values());
- System.out.println(set);
6.list转数组
- List list = Arrays.asList("a","b");
- System.out.println(list);
- String[] arr = (String[])list.toArray(new String[list.size()]);
- System.out.println(Arrays.toString(arr));
7、文件读取
- public String readFile(String fileName) throws Exception {
- String fileContent = "";
- File f = new File(fileName);
- FileReader fileReader = new FileReader(f);
- BufferedReader reader = new BufferedReader(fileReader);
- String line = "";
- while (line = reader.readLine() != null) {
- String fileContent = fileContent + line;
- }
- reader.close();
- return fileContent;
- }
8、httpclient获取资源
- HttpClient httpClient = new HttpClient();
- GetMethod getMethod = new GetMethod("http://www.sina.com.cn/");
- //getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
- try {
- int statusCode = httpClient.executeMethod(getMethod);
- if (statusCode == HttpStatus.SC_OK) {
- byte[] body = getMethod.getResponseBody();
- String content = new String(body);
- System.out.println(content);
- }
- } catch (HttpException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
9、retry保障功能的健壮性
- private static Logger logger = LoggerFactory.getLogger(Retry.class);
- private static int retryTimes = 10;
- public static void main(String[] args) {
- StringBuffer errorMsg = new StringBuffer();
- for (int i = 0; i <= retryTimes; i++) {
- HttpClient httpClient = new HttpClient();
- GetMethod getMethod = new GetMethod("http://www.bai000000000000.com/");
- //getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
- try {
- int statusCode = httpClient.executeMethod(getMethod);
- if (statusCode == HttpStatus.SC_OK) {
- byte[] body = getMethod.getResponseBody();
- String content = new String(body);
- System.out.println(content);
- break;
- }
- } catch (Exception e) {
- if (i >= retryTimes) {
- errorMsg.append("after ").append(retryTimes)
- .append(" times retry, still failed to connect the url");
- logger.error(errorMsg.toString(),e);
- throw new RuntimeException(errorMsg.toString(), e);
- }
- logger.warn("connect the url " + i + " time.",e);
- }
- }
- }
10、BufferedImage image与byte之间转换
请问怎么从BufferedImage image得到byte[]数据。
我现在已经有BufferedImage image, 怎么得到一个byte[]的数组呢??
但是不要经过文件转。否则太慢了了。
------解决方案--------------------------------------------------------
BufferedImage srcImage = ImageIO.read(new File( "c:/xxx.jpg "));
byte[] data = ((DataBufferByte) srcImage.getData().getDataBuffer()).getData();
------解决方案--------------------------------------------------------
一个BufferedImage可以得一个Int[]数组.用它的getRGB方法.取得的是它的相素信息.
从一个int[]到BufferedImage可以用MemoryImageSource.
我想取得byte[]数组是没有什么意义的.当然不是不可以实现.用ImageIO类.
BufferedImage bi=ImageIO.read(new ByteArrayInputSream(byte[]);
ImageIO.write(bufferedImage, "gif ",new ByteArrayOutputStream(new byte[20000]));然后你就可以从这个ByteArrayOutputStream取得你想要的byte啦!
不过这样一点意义也没有,你无法改任何相素.
11、获取完整的请求路径
- String url = req.getRequestURL().toString();
- String queryString = req.getQueryString();
- System.out.println(url + "?" + queryString);
如:http://localhost:8080/MyServlet??q=a?q1=a1
12、标准String数组输出
- private static String toString(String[] fileNames) {
- StringBuffer outline = new StringBuffer("[");
- for (int i = 0; i < fileNames.length; i++) {
- outline.append(fileNames[i]);
- if (i != fileNames.length - 1)
- outline.append(",");
- }
- outline.append("]");
- return outline.toString();
- }
13、从request中获取servletContext(即application)
request.getSession().getServletContext();
14、初始化日志写法
在strtus2中FilterDispatcher类中的写法
- private Logger log;
- private void initLogging() {
- String factoryName = filterConfig.getInitParameter("loggerFactory");
- if (factoryName != null) {
- try {
- Class cls = ClassLoaderUtil.loadClass(factoryName, this.getClass());
- LoggerFactory fac = (LoggerFactory) cls.newInstance();
- LoggerFactory.setLoggerFactory(fac);
- } catch (InstantiationException e) {
- System.err.println("Unable to instantiate logger factory: " + factoryName + ", using default");
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- System.err.println("Unable to access logger factory: " + factoryName + ", using default");
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- System.err.println("Unable to locate logger factory class: " + factoryName + ", using default");
- e.printStackTrace();
- }
- }
- log = LoggerFactory.getLogger(FilterDispatcher.class);
- }
15、警告写法:Spring中样例开头大写,无.结尾
Assert.notNull(paths, "Path array must not be null");
Assert.notNull(clazz, "Class argument must not be null");
16、URL的编解码
- try {
- String codes = URLEncoder.encode("卓越 新书C#入门", "UTF-8");
- System.out.println(codes);
- String text = URLDecoder.decode(codes, "UTF-8");
- System.out.println(text);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
17、十六进制转换与Long的相互转换
- String a = "32cda6f174e3";
- String b= "374ccd2f2496";
- long l = Long.valueOf(a, 16);
- l += Long.valueOf(b, 16);
- System.out.println(Long.toHexString(l));
MD5中一部分进行运算
18、将byte[]编码为16进制的字符串
- private String encodeHex(byte[] data) {
- final char[] toDigits = {'0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
- int l = data.length;
- char[] out = new char[l << 1];
- // two characters form the hex value.
- for (int i = 0, j = 0; i < l; i++) {
- out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
- out[j++] = toDigits[0x0F & data[i]];
- }
- return new String(out);
- }
19、获取执行时当前行的行号、方法、类
- new Throwable().getStackTrace()[0].getLineNumber()
- new Throwable().getStackTrace()[0].getClassName()
- new Throwable().getStackTrace()[0].getMethodName()
20、Java中的回调:定义接口,让调用者去实现,最后调到调用者自己写的实现 -- 回调
如果我们要测试一个类的方法的执行时间,通常我们会这样做:
- public class TestObject {
- /**
- * 一个用来被测试的方法,进行了一个比较耗时的循环
- */
- public static void testMethod(){
- for ( int i= 0 ; i< 100000000 ; i++){
- }
- }
- /**
- * 一个简单的测试方法执行时间的方法
- */
- public void testTime(){
- long begin = System.currentTimeMillis(); //测试起始时间
- testMethod(); //测试方法
- long end = System.currentTimeMillis(); //测试结束时间
- System.out.println("[use time]:" + (end - begin)); //打印使用时间
- }
- public static void main(String[] args) {
- TestObject test=new TestObject();
- test.testTime();
- }
- }
大家看到了testTime()方法,就只有"//测试方法"是需要改变的,下面我们来做一个函数实现相同功能但更灵活:
首先定一个回调接口:
- public interface CallBack {
- //执行回调操作的方法
- void execute();
- }
然后再写一个工具类:
- public class Tools {
- /**
- * 测试函数使用时间,通过定义CallBack接口的execute方法
- * @param callBack
- */
- public void testTime(CallBack callBack) {
- long begin = System.currentTimeMillis(); //测试起始时间
- callBack.execute(); ///进行回调操作
- long end = System.currentTimeMillis(); //测试结束时间
- System.out.println("[use time]:" + (end - begin)); //打印使用时间
- }
- public static void main(String[] args) {
- Tools tool = new Tools();
- tool.testTime(new CallBack(){
- //定义execute方法
- public void execute(){
- //这里可以加放一个或多个要测试运行时间的方法
- TestObject.testMethod();
- }
- });
- }
- }
大家看到,testTime()传入定义callback接口的execute()方法就可以实现回调功能
本文转自 tianya23 51CTO博客,原文链接:http://blog.51cto.com/tianya23/841827,如需转载请自行联系原作者