见代码
public static boolean checkExist(String filepath) throws Exception {
log.info("开始检查文件:"+filepath);
File file = new File(filepath);
File file2 = new File(file.getParent());
if (file2.isDirectory()) {// 判断文件目录是否存在
log.info("文件目录存在!");
} else {
log.info("文件目录不存在!");
file2.mkdirs();
log.info("创建文件目录成功!");
}
if (file.exists()) {//判断文件是否存在
log.info("文件存在!");
if (0 < file.length()) {//判断文件是否为空
return true;
} else {
log.info("但文件为空");
}
} else {
file.createNewFile();// 创建文件
log.info("文件不存在,创建文件成功!");
}
return false;
}再送一个写入到文件的代码
public static void save(File file, String data, String encoding) throws IOException{
OutputStream outStream = null;
OutputStreamWriter outWriter = null;
try{
outStream = new FileOutputStream(file);
outWriter = new OutputStreamWriter(outStream,encoding);
outWriter.write(data);
}finally{
if(outWriter!=null)outWriter.close();
if(outStream!=null)outStream.close();
}
}如有雷同,算我抄你的
本文提供了两个实用的Java方法:检查指定路径的文件是否存在及其所属目录是否完整,并在必要时自动创建;另一个方法用于将字符串数据写入指定文件中。通过这两个方法,开发者可以轻松地实现文件的检查和数据的保存。
776

被折叠的 条评论
为什么被折叠?



