package com.sgcc; import java.io.*; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Main { public static String generateMixedString(int length) { Random random = new Random(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { // 生成随机数,当生成的数字为0时,表示生成字母,生成数字为1时,表示生成数字; int type = random.nextInt(2); if (type == 0) { // 生成随机字母(小写) char letter = (char) (random.nextInt(26) + 'a'); sb.append(letter); } else { // 生成随机数字 char digit = (char) (random.nextInt(10) + '0'); sb.append(digit); } } return sb.toString().toUpperCase(); } public static void main(String[] args) { //示例一: 生成5个长度,随机字符串 Main m = new Main(); String result = m.generateMixedString(5); System.out.println(result); System.out.println("------------------------------------"); //示例二: 生成18为长度不重复字符串,前6位为随机字母和数字,后12位为数字序列 int limitNum = 10; DecimalFormat df = new DecimalFormat("000000000000"); StringBuffer stringBuffer = new StringBuffer(); for (int i=0 ;i < limitNum;i++){ stringBuffer.append(generateMixedString(6) + df.format(i)).append("\n"); } //示例三:将数据写入到文件 String filePath = "result.txt"; try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) { writer.write(stringBuffer.toString()); } catch (IOException e) { e.printStackTrace(); } //示例四:读取文件 final String CHARSET_NAME = "UTF-8"; List<String> content = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), CHARSET_NAME))) { String line; while ((line = br.readLine()) != null) { content.add(line); } } catch (Exception e) { e.printStackTrace(); } // 输出list中每一行的内容 // content.forEach(System.out::println); // 根据下表获取List每一行的内容 for (int i=0;i<content.size();i++){ System.out.println(content.get(i)); } } }
标签:文件,String,int,生成,随机,import,字符串,new From: https://www.cnblogs.com/yeyuzhuanjia/p/18217398