据说这是一道点招题?
package 测试;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
public class Test1 {
/**
* 题目:
* 将用户在控制台上输出的5个数字按照大小顺序存入到D:\\xx.txt中
* 并以相反的的顺序读出显示在控制台上
*
* 分析:
* 1,创建键盘录入对象,将录入的数据存入一个TreeSet<Integer>集合中(自动排序)
* 2,遍历TreeSet集合,将其中的元素依次写入D:\\xx.txt中
* 3,从D:\\xx.txt中读入数据,并将其存入一个ArrayList<Integer>中
* 4,倒序遍历ArrayList集合,并将其结果输出在控制台
*
* @throws Exception
*/
public static void main(String[] args) throws Exception {
TreeSet<Integer> ts = getTreeSet();
writeFile(ts);
print();
}
// 录入数据并将其存入至TreeSet集合中(自动排序)
public static TreeSet<Integer> getTreeSet() {
TreeSet<Integer> ts = new TreeSet<>();
Scanner sc = new Scanner(System.in);
System.out.println("请从键盘录入5个整数(请勿重复):");
while (ts.size() < 5) {
String line = null;
try {
line = sc.nextLine();
ts.add(Integer.parseInt(line));
} catch (Exception e) {
try {
new BigInteger(line);
System.out.println("您输入的整数过大,请重新输入:");
} catch (Exception e2) {
try {
new BigDecimal(line);
System.out.println("您输入的是一个小数,请重新输入:");
} catch (Exception e3) {
System.out.println("您输入的是一个字符串,请重新输入:");
}
}
}
}
return ts;
}
// 遍历TreeSet集合,将其中的元素依次写入D:\\xx.txt中
public static void writeFile(TreeSet<Integer> ts) throws Exception {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(
"D://xx.txt")); MyClose mc = new MyClose();) {
for (Integer integer : ts) {
bw.write(integer + "");
bw.newLine();
}
}
}
// 将从文件中读入的数据倒序显示在控制台
public static void print() throws Exception {
ArrayList<Integer> list = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(
"D://xx.txt")); MyClose mc = new MyClose();) {
String line;
while ((line = br.readLine()) != null)
list.add(Integer.parseInt(line));
}
System.out.print("倒序显示:");
for (int i = list.size() - 1; i >= 0; i--)
System.out.print(list.get(i) + " ");
}
}
// 异常处理
class MyClose implements AutoCloseable {
@Override
public void close() throws Exception {
}
}
|
|