[Java] 纯文本查看 复制代码
package base3;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/*
* 3.将用户在控制台上输入5个数字,按照降序存入到“D:\\number.txt”中
*/
public class Demo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("请输入五个数字");
int i = 0;
ArrayList<Integer> list = new ArrayList<>();
while(i<5){
int next = sc.nextInt();
list.add(next);
i++;
}
System.out.println(list);
//将集合变成数组
Object[] array = list.toArray();
//将数组变成升序排列
Arrays.sort(array);
//将数组变成字符串
String string = Arrays.toString(array);
//将字符串变成字符串缓冲类
StringBuffer sb = new StringBuffer(string);
//将字符串翻转
StringBuffer re = sb.reverse();
//去除两头的中括号
String substring = re.substring(1, re.length()-1);
//打印数组
System.out.println(substring);
//将数组写入到文本中
FileWriter fw= new FileWriter(new File("d:\\number.txt"));
fw.write(substring);
fw.close();
}
}
[Java] 纯文本查看 复制代码
package com.heima.collection;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Test09 {
public static void main(String[] args) throws Exception {
List<Integer> list = new LinkedList<Integer>();
//集合长度小于5就添加
while (list.size()<5) {
list.add(new Scanner(System.in).nextInt());
}
//排序 逆序
Collections.sort(list);
Collections.reverse(list);
//创建输出流
FileOutputStream fos = new FileOutputStream("number.txt");
for (Integer integer : list) {
fos.write(String.valueOf(integer).getBytes());
fos.write("\r\n".getBytes());
}
fos.close();
}
}