Java使用点滴

1. 如何产生一定范围内的随机数字(0~Max之间的数字[0,max))

 

Random random = new Random();
Math.abs(random.nextInt() % Max)];

或者

(int)(Math.random() * Max)

 

2. 如何将字节流转换成字符流

 

new BufferedReader(new InputStreamReader(xx.getInputStream))


3. Arrays是一个工具类,在java.util包里面,提供了很实用的静态方法,熟悉这些方法可以使得代码更精炼。

   1) String toString(Object[] o) (jdk1.5)

      如果o不为空,等同于Arrays.asList(o).toString()

import java.util.Arrays;
public class CounterObject {
         private static long count = 0;
         public String toString(){
              return "Object " + count++;
         }
         public static void main(String[] args){
         CounterObject[] counterObjects = new CounterObject[5];
         for(int i= 0; i < counterObjects.length; i++)
         {
         counterObjects[i] = new CounterObject();
         }
         System.out.println(Arrays.toString  (counterObjects));
         }
     }
 

输出结果为[Object 0, Object 1, Object 2, Object 3, Object 4]
类似的方法有 toString(int[] a) toString(char[] a) toString(long[] a)...

    2) List asList(T...a)
    提供了从Array转换到Collection的接口

 

    List intList = new ArrayList( Arrays.asList(0, 1, 2, 3, 4, 5));

    List stooges = Arrays.asList("Larry", "Moe", "Curly"); 
 

  3) fill(Object[] a, Object val)

 

String[] str = new String[6];
Arrays.fill(str, "hello");

   类似的方法有 fill(int[] a, int val)   fill(long[] a, long val)...

 

 

 

4.  如何将字串 String 转换成整数 int

Integer.parseInt("123"); 

Integer.valueOf("123").intValue();  

 

 字串转成 Double, Float, Long 与此类似 

5 如何将整数 int 转换成字串 String

String s = String.valueOf(i);

String s = Integer.toString(i); 

String s = "" + i; 

6 如何将InputStream转换成byte数组

private static byte[] transformInputstream(InputStream input)throws Exception
    {
        byte[] byt= null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int b=0;      
        b = input.read();
        while( b != -1)
        {
            baos.write(b);
            b = input.read();            
        }
        byt = baos.toByteArray();
        return byt;
    }
 
7 如何删除一个文件夹下面的所有文件夹及文件(递归调用)
 
	public void deleteAll(String filePath) {
		File f = new File(filePath);
		if (f.exists() && f.isDirectory()) {
			if (f.listFiles().length == 0) {
				f.delete();
			} else {
				File[] delFiles = f.listFiles();
				for (File delFile : delFiles) {
					if (delFile.isDirectory()) {
						deleteAll(delFile.getAbsolutePath());
					}
					delFile.delete();
				}
			}
		}
	}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值