键盘录入五个数,进行排序后 写入一个txt文件中, 然后在从txt文件读取到控制台输出。
- import java.io.BufferedReader;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.Comparator;
- import java.util.Scanner;
- import java.util.TreeSet;
- public class Demo {
- public static void main(String[] args) throws IOException {
- Scanner sc = new Scanner(System.in);
- TreeSet<String> ts = new TreeSet<>(new Comparator<String>(){
- @Override
- public int compare(String o1, String o2) {
- int num = o1.compareTo(o2);
- return num==0?1:num;
- }
-
- });
- System.out.println("请输入五个数");
- while(ts.size()<5){
- String s = sc.nextLine();
- ts.add(s);
- }
-
- FileOutputStream fos = new FileOutputStream("a.txt");
- for(String i:ts){
- fos.write(i.getBytes());
- fos.write("\r\n".getBytes());
- }
- fos.close();
- System.out.println("写入完毕");
-
- BufferedReader br = new BufferedReader(new FileReader("a.txt"));
- String len;
- while((len=br.readLine())!=null){
- System.out.println(len);
- }
- br.close();
- }
- }
复制代码 |