读写文件操作在Java程序开发常常用到的。因此,我封装了一个工具类专门用于读取文件内容、向文件写入内容的工具类。代码如下:
public class FileUtils {
public static void main(String[] args) {
//system.out.println(file.separator);
try {
test1();
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
}
public static void test1() throws IOException {
String dirPath = "E:\\Program Files\\JavaIDE2017\\JavaWebDemo\\FileOperationDemo\\src";
String fileName = "test.txt";
String content = readFileContent(dirPath + File.separator + fileName);
System.out.println(content);
writerContentToFile(dirPath, "test1.txt", content);
}
/**
* 判断文件是否存在
*
* @param filePath
* @return
*/
public static boolean isFileExists(String filePath) {
return new File(filePath).exists();
}
/**
* 判断文件是否是目录
*
* @param filePath
* @return
*/
public static boolean isDirectoty(String filePath) {
return new File(filePath).isDirectory();
}
/**
* 读取文件的内容
*
* @param filePath
* @return
* @throws IOException
*/
public static String readFileContent(String filePath) throws IOException {
StringBuilder sb = new StringBuilder();
File file = new File(filePath);
if (!file.exists()) {
throw new IOException("指定文件不存在:" + filePath);
}
if (file.isDirectory()) {
throw new IOException("指定文件是一个文件夹:" + filePath);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String str;
while (null != (str = bufferedReader.readLine())) {
sb.append(str).append("\n");
}
bufferedReader.close();
return sb.toString();
}
/**
* 向指定文件写入内容
*
* @param parentDirPath 文件父目录
* @param fileName 输出文件名
* @param content 写入内容
* @throws IOException
*/
public static void writerContentToFile(String parentDirPath, String fileName, String content) throws IOException {
File parentDir = new File(parentDirPath);
if (!parentDir.exists()) {
throw new IOException("输出文件父目录不存在:" + parentDirPath);
}
BufferedWriter bufferedWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(parentDirPath + File.separator + fileName)));
bufferedWriter.write(content);
bufferedWriter.close();
}
}