Java 检查文件后生成8位随机数
先检查目标文件中是否有数据,如果有则不执行操作,没有就生成一个新的8位随机数。
import java.io.*;
import java.util.Objects;
public class WRandom {
public static void main(String[] args) throws IOException {
String s = "";
File file = new File("C:\\Users\\空政\\Desktop\\2.txt");
String c = txt2String(file);
if (Objects.equals(c, "")){
System.out.println("原文件为空,生成新的随机数");
//生成8位随机数
for (int i=0;i<8;i++){
// int n = (int) (Math.random()*9);
String m = String.valueOf((int) (Math.random()*9));//转换成字符串
s = s + m;//拼接字符串
System.out.println(s);
}
//输出至txt文件
Writer out =new FileWriter(file);
String data=s;
out.write(data);
out.close();
System.out.println("已输出8位随机数");
}else {
System.out.println("文件不为空");
}
}
//读取txt的方法
public static String txt2String(File file){
String result = "";
try{
BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
String s = null;
while((s = br.readLine())!=null){//使用readLine方法,一次读一行
result = result + "\n" +s;
}
br.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}