在File类中并没有提供判断文件是否为空的方法,但可以借助length()方法的返回值进行判断。如果文件不存在或文件为空时,length()方法返回值为0,可以以此判断,举个小栗子。
读取文件中的数据,排序后再次写到本地文件
public class CharStreamDemo2 {
public static void main(String[] args) throws IOException {
//需求:读取文件中的数据,排序后再次写到本地文件
//思路分析:
//判断文件是否存在如果不存在,那么就创建文件写入内容
//创建文件
//写入数据到文件
File f = new File("D:\\project\\charstream\\sort.txt");
boolean exists = f.exists();
if (!exists||(exists && f.length()==0)) {
FileWriter fw = new FileWriter("D:\\project\\charstream\\sort.txt");
String array = "9 1 2 5 3 10 4 6 7 8";
fw.write(array);
fw.close();
} else {
System.out.println("文件已存在");
}
//把文件中的数据读取出来
BufferedReader br = new BufferedReader(new FileReader("D:\\project\\charstream\\sort.txt"));
String line = br.readLine();
System.out.println("读取到的数据为" + line);
br.close();
//按照空格进行拆分
String[] split = line.split(" ");
//把字符串转化为int类型
int[] array=new int[split.length];
//遍历spilt
for (int i = 0; i < split.length; i++) {
String smallStr=split[i];
int number = Integer.parseInt(smallStr);
//转化后结果存到array数组中
array[i]=number;
}
//排序
Arrays.sort(array);
System.out.println("排序后的数字为"+Arrays.toString(array));
//把结果再次写入文件
BufferedWriter bw=new BufferedWriter(new FileWriter("D:\\project\\charstream\\sort.txt"));
//写入
for (int i = 0; i < array.length; i++) {
bw.write(array[i]+" ");
}
bw.flush();
bw.close();
}
}