项目常用功能代码 随机字符串

一些小的小工具代码

/** 产生一个随机的字符串*/  
public static String RandomString(int length) {  
    String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  
    Random random = new Random();  
    StringBuffer buf = new StringBuffer();  
    for (int i = 0; i < length; i++) {  
        int num = random.nextInt(62);  
        buf.append(str.charAt(num));  
    }  
    return buf.toString();  
}  

# java生成指定范围的随机数 ``` import java.util.Random;

public class RandomTest {
public static void main(String[] args) {
int max=20;
int min=10;
Random random = new Random();

    int s = random.nextInt(max)%(max-min+1) + min;
    System.out.println(s);
}

}


<br/>
# 时间戳
    String pname = "a";
    Random rand = new Random();
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
    String time = df.format(new Date());
    int randnum1 = rand.nextInt(900)+100;
        time=time.concat(String.valueOf(randnum1));
    int randnum2 = rand.nextInt(90)+10;
        time=time.concat(String.valueOf(randnum2));
    pname=time;
    String imgPath = "C:/Users/Administrator/Desktop/Timecode/"+pname+".png";


<br/>
# 读写text文件

import java.io.File;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;

public class cin_txt {
static void main(String args[]) {
try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw

        /* 读入TXT文件 */  
        String pathname = "D:\twitter\13_9_6\dataset\en\input.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径  
        File filename = new File(pathname); // 要读取以上路径的input。txt文件  
        InputStreamReader reader = new InputStreamReader(  
                new FileInputStream(filename)); // 建立一个输入流对象reader  
        BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言  
        String line = "";  
        line = br.readLine();  
        while (line != null) {  
            line = br.readLine(); // 一次读入一行数据  
        }  

        /* 写入Txt文件 */  
        File writename = new File(".\result\en\output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件  
        writename.createNewFile(); // 创建新文件  
        BufferedWriter out = new BufferedWriter(new FileWriter(writename));  
        out.write("我会写入文件啦
"); // 
即为换行  
        out.flush(); // 把缓存区内容压入文件  
        out.close(); // 最后记得关闭文件  

    } catch (Exception e) {  
        e.printStackTrace();  
    }  
}  

}


<br/>
# 计算代码时间

long startTime=System.currentTimeMillis(); //获取开始时间
doSomeThing(); //测试的代码段
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");


![](https://www.yueduwen.com/uploads/allimg/1604/1-160421213J6116.jpg)