题目要求:
1.创建一个SetRead类,要求能够将20个0~1000的随机整数无序写入D:\test.txt中,整数之间用一个空格分开。
2.创建一个ToSort类,能够读取D:\test.txt中的所有整数,然后降序输出这些整数。
main函数以给出,如下所示:
public static void main(String[] args) throws IOException {
String Path="D:\\test.txt";
SetRead(Path,1000);
ToSort(Path);
}
没有需求分析,直接奉上源代码
解题源代码:
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.ThreadLocalRandom;
public class ReSort {
public static void SetRead(String path,int bound) throws IOException {
File file=new File(path);
FileWriter fileWriter=new FileWriter(file);
//首先要确保txt文件存在
if (!file.exists()) {
boolean flag=file.createNewFile();
}else {
//多线程不重复随机数:ThreadLocalRandom;比普通的random方法更靠谱
ThreadLocalRandom random=ThreadLocalRandom.current();
int RandomNum=0;
//依次将20个随机整数写入test.txt中
for (int i = 0; i <20; i++) {
RandomNum=random.nextInt(bound);
fileWriter.write(RandomNum+" ");
fileWriter.flush();
}
fileWriter.close();
}
}
public static void ToSort(String path) throws IOException {
FileInputStream fileInputStream=new FileInputStream(path);
InputStreamReader reader=new InputStreamReader(fileInputStream);
BufferedReader bf=new BufferedReader(reader);
String str="";
while ((str=bf.readLine())!=null){
String nums[]=str.split(" "); //字符串按空格分割
Integer[] number=new Integer[nums.length];
for (int i = 0; i < nums.length; i++) {
number[i]=Integer.parseInt(nums[i].trim());
}
//sort的降序排序,然后输出
Arrays.sort(number, Collections.reverseOrder());
for (int i = 0; i < nums.length; i++) {
System.out.printf(number[i]+" ");
}
}
bf.close();;
}
public static void main(String[] args) throws IOException {
String Path="D:\\test.txt";
SetRead(Path,1000);
ToSort(Path);
}
}