Java 对文件进行相关操作
整理比较常见的方法
方法一:读取指定文件中的内容
/**
* 方法一:读取指定文件中的内容
*
* @param path
* @return
* @author 小辰哥哥
*/
public static String readContent(String path) {
File file = new File(path);
// result 用来存放读取到的内容
StringBuilder result = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String s = null;
// readLine方法表示一行一行的读取内容
while ((s = br.readLine()) != null) {
// 将内容放入result中
result.append(System.lineSeparator() + s);
}
// 关闭资源
br.close();
} catch (Exception e) {
e.printStackTrace();
}
// 去掉内容中的换行字符
return result.toString().replaceAll("\r|\n", "");
}
方法调用:
readContent("D:\\MyComputer\\小辰哥哥.txt")
方法二:写入文件中,并覆盖其原内容
/**
* 方法二:写入文件中,并覆盖其原内容
*
* @param Content
* @param filepath
* @return
* @author 小辰哥哥
*/
public static boolean writeFile(String Content, String filepath) {
boolean flag = false;
try {
// 写入的文件的路径
PrintWriter pw = new PrintWriter(filepath);
// 写入的内容
pw.write(Content);
pw.flush();
pw.close();
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
方法调用:
writeFile("Hello World", "D:\\MyComputer\\小辰哥哥.txt")
方法三:删除某个文件夹下的所有文件夹和文件
/**
* 方法三:删除某个文件夹下的所有文件夹和文件
*
* @param delpath
* @return
* @author 小辰哥哥
*/
public static boolean deletefile(String delpath) {
try {
File file = new File(delpath);
if (!file.isDirectory()) {
file.delete();
System.out.println("单文件已删除");
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "\\" + filelist[i]);
if (!delfile.isDirectory()) {
System.out.println("删除文件绝对路径:" + delfile.getAbsolutePath());
System.out.println("删除文件名称:" + delfile.getName());
delfile.delete();
} else if (delfile.isDirectory()) {
deletefile(delpath + "\\" + filelist[i]);
}
}
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
方法调用:
deletefile("D:\\MyComputer\\删除测试")
方法四:读取某个文件夹下的所有文件
/**
* 方法四:读取某个文件夹下的所有文件
*
* @param filepath
* @return
* @author 小辰哥哥
*/
public static boolean readfile(String filepath) {
try {
File file = new File(filepath);
if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "/" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("文件名称:" + readfile.getName());
System.out.println("文件绝对路径:" + readfile.getAbsolutePath());
} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
方法调用:
readfile("D:\\MyComputer\\读取文件")
总结
每天一个提升小技巧!!!