今天有一个任务就是接收数据,然后将数据写到文件,在网上查看了很多,也尝试也很多,都不太对,总是报找不到文件,弄了一晚上,写了一个比较严谨的代码,然后就没有出过错了,就想起了大学学的程序的健壮性,严谨== 正确。
private static void createFile(byte[] data) {
BufferedOutputStream bos = null;
File file = null;
try {
// start -------------------创建文件的严谨
File dir = new File(FILE_PATH);
if (dir.exists() || dir.mkdirs()) { // 严谨 == 正确
System.out.println(dir.getPath());
}
file = new File(FILE_PATH, "data_" + count + ".txt");
if (file.exists() || file.createNewFile()) {// 严谨 == 正确
System.out.println(file.getName());
}
// end --------------------
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(data);
bos.flush();
System.out.println("success " + count);
count++;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}