1.list转set
2.set转list
3.数组转为list
此时stooges中有有三个元素。注意:此时的list不能进行add操作,否则会报“java.lang.UnsupportedOperationException”,Arrays.asList()返回的是List,而且是一个定长的List,所以不能转换为ArrayList,只能转换为AbstractList
原因在于asList()方法返回的是某个数组的列表形式,返回的列表只是数组的另一个视图,而数组本身并没有消失,对列表的任何操作最终都反映在数组上. 所以不支持remove,add方法的
4.数组转为set
5.map的相关操作。
6.list转数组
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中的回调:定义接口,让调用者去实现,最后调到调用者自己写的实现 -- 回调
如果我们要测试一个类的方法的执行时间,通常我们会这样做:
大家看到了testTime()方法,就只有"//测试方法"是需要改变的,下面我们来做一个函数实现相同功能但更灵活:
首先定一个回调接口:
然后再写一个工具类:
大家看到,testTime()传入定义callback接口的execute()方法就可以实现回调功能