生成10位16进制的数
public class ReadDeviceNo {
// 获取一个String值
public static String getString(Context context) {
//读器SD卡文件 获取设备序列号 (如果有,读取这个序列号,没有就随机产生一个10位16进制的数)
File file = new File(getFilePath(context));
String num = "";
if (file.exists()) {
num = ReadTxt(file);
}
//判断这个数字 是否存在 并且长度是否等于10
if (TextUtils.isEmpty(num) && num.length() != 10) {
//随机生成1个10位进制的随机数
num = getRandomValue(10);
write(file, num);
}
return num;
}
//获取获取随机数
private static String getFilePath(Context context) {
String directoryPath = "";
//判断SD卡是否可用
if (MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
directoryPath = "mnt/sdcard";
} else {
//没内存卡就存机身内存
directoryPath = context.getCacheDir().getAbsolutePath();
}
String filePath = directoryPath + File.separator + "cl.txt";
File file = new File(directoryPath);
if (!file.exists()) {//判断文件目录是否存在
file.mkdirs();
}
return filePath;
}
//读取txt文件
private static String ReadTxt(File file) {
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行
result.append(s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
/*产生numSize位16进制的数*/
public static String getRandomValue(int numSize) {
String str = "";
for (int i = 0; i < numSize; i++) {
char temp = 0;
int key = (int) (Math.random() * 2);
switch (key) {
case 0:
temp = (char) (Math.random() * 10 + 48);//产生随机数字
break;
case 1:
temp = (char) (Math.random() * 6 + 'a');//产生a-f
break;
default:
break;
}
str = str + temp;
}
return str;
}
private static void write(File file, String content) {
try {
if (!file.exists()) {
file.createNewFile();
}
StringBuilder sb = new StringBuilder();
sb.append(content);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(file.length());
raf.write(sb.toString().getBytes());
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
随机数 生成10位16进制的数
最新推荐文章于 2022-07-12 11:30:23 发布