Java读写文件操作

读写文件操作在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();
    }

}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值