将用户在控制台上输出的5个数字按照大小顺序存入
* 到D:\\xx.txt中并以相反的的顺序读出显示在控制台上
public class Test03 {
public static void main(String[] args) throws IOException {
//File file = new File("num1.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter("num1.txt"));//1.创建文件输出流关联文件对象
Scanner sc = new Scanner(System.in);//2.创建键盘录入对象
System.out.println("请输入一个整数");
TreeSet<Integer> ts = new TreeSet<Integer>(new Comparator<Integer>() { //3.创建treeset集合,传入比较器,按从大到小排序
@Override
public int compare(Integer i1, Integer i2) {
int num = i2.compareTo(i1);
return num == 0 ? 1 : num;
}
});
while (ts.size() < 5) {//4.以输入的数据的长度做判断,如果小于5就将数据转换成integer类型存入
// try {
String line = sc.nextLine();
Integer i = Integer.parseInt(line);
ts.add(i);
//} catch (Exception e) {
//System.out.println("类型输入错误,请重新输入");
//}
}
bw.write(ts.toString()); //5.输出流写出对象,转换成字符串
bw.close();//6.关流
BufferedReader br = new BufferedReader(new FileReader("num1.txt"));//7.创建文件输入流对象,关联文件
String line = br.readLine();//8.每次读取一行
StringBuffer sb = new StringBuffer(line.substring(1, line.length() - 1)); //9.创建stringbuffer对象获取字符串的信息
sb = sb.reverse();//.insert(0, "[").append("]"); //10.反转字符串
System.out.println(sb);
br.close(); //关流
}
} |
|