package BasicFileFuntion;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class BasicFileFuntion {
public static void main(String[] args){
;
}
/*
* 函数名称:private static File createFile(String filepath)
* 输入参数:filepath:创建文件的路径
* 输出参数:fr:指向文件的引用
* 功能描述:函数作用为在指定位置创建一个文件,若存在文件则直接返回指向文件的引用,不存在则创建一个文件并返回引用
*/
public static File createFile(String filepath){
File fr = new File(filepath);
if(fr.exists()&&fr.isFile()){//检查文件是否存在
System.out.println("使用路径下已经存在的文件夹:"+filepath);
}else{
try{
if(fr.createNewFile()){//不存在则创建文件
System.out.println("创建"+fr.getName()+"文件!");
}else{
System.out.println("创建"+filepath+"文件失败!");
return null;
}
}catch(IOException e){
System.out.println("创建文件失败,错误信息为:"+e.getMessage());
return null;
}
}
return fr;//返回指向文件的引用
}
/*
* 函数名称:private static boolean deleteFile(String filepath)
* 输入参数:fr:需要删除的文件
* 输出参数:true or false:删除文件的结果
* 功能描述:函数作用为删除指定路径的文件,并返回操作的结果
*/
public static boolean deleteFile(File fr){
// File fr = new File(filepath);
if(fr == null){
System.out.println("文件引用指向为空,请检查程序代码!");
return false;
}
if(fr.exists()&&fr.isFile()){
if(fr.delete()){
System.out.println("已删除"+fr.getName()+"文件!");
return true;
}else{
System.out.println("删除"+fr.getName()+"文件失败!");
return false;
}
}else{
System.out.println("指定文件路径不存在!");
return false;
}
}
/*
* 函数名称:private static File renameFile(String oldfilename, String newfilename)
* 输入参数:oldfilename:命名文件的路径 newfilename:命名后的文件路径
* 输出参数:fr:指向新命名文件的引用
* 功能描述:函数作用为对文件进行重命名操作
*/
public static File renameFile(String oldfilename, String newfilename){
File fr1 = new File(oldfilename);
if(!fr1.exists()){
System.out.println("路径"+oldfilename+"文件不存在!");
return null;
}
File fr2 = new File(newfilename);
if(fr2.exists()&&fr2.isFile()){
System.out.println("路径"+newfilename+"文件已被占用!");
return null;
}else{
if(fr1.renameTo(fr2)){
System.out.println("文件"+fr1.getName()+"重命名成功!");
return fr2;
}else{
System.out.println("文件"+fr1.getName()+"重命名失败!");
return null;
}
}
}
/*
* 函数名称:private static File renameFile(String oldfilename, String newfilename)
* 输入参数:file:需要打印的文件
* 输出参数:无
* 功能描述:函数作用为对文件进行打印操作
*/
public static void printFile(File file){
System.out.println("文件中的内容为:\n");
try{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String text = "";
while((text = br.readLine()) != null){
System.out.println(text);
}
System.out.println(file.getName()+"文件内容读取结束!");
fr.close();
br.close();
}catch(IOException e){
System.out.println(file.getName()+"文件读取失败,错误信息为:"+e.getMessage());
}
}
//待添加..
}
操作File文件的一些基本打包函数
最新推荐文章于 2022-01-25 10:22:05 发布