多种编程语言的文件读写操作

5 篇文章 0 订阅
3 篇文章 0 订阅

java

FileUtil 静态工具类

在测试过程我们经常需要对文件进行读写操作,而在使用 Java原生的 fileReader 和 fileWriter 会产生不必要的冗余(例如读取文本内容的 while 循环)。所以我们需要对它们进行二次封装,简化工具以方便日常使用。

package com.raoLong;


import java.io.*;

/**
 * Author:   RaoQingLong
 * Date:     2021/6/26 22:11
 * Description: 读取文件
 */

public class FileUtil {
    protected static FileReader fileReader;
    protected static FileWriter fileWriter;


    protected static boolean checkFile(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    protected static String read(File file) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            fileReader = new FileReader(file);
            char[] container = new char[1024];
            int readLength;
            while ((readLength = fileReader.read(container)) != -1) {
                String onceContent = new String(container, 0, readLength);
                stringBuilder.append(onceContent);
            }
            fileReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    static String read(String filePath) {
        boolean isFileExist = checkFile(filePath);
        if (isFileExist) {
            File file = new File(filePath);
            return read(file);
        } else {
            return null;
        }
    }

    protected static void write(File file, String content) {
        try {
            fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void write(String filePath, String content) {
        File file = new File(filePath);
        write(file, content);
    }

    static void append(String filePath, String content) {
        // 首先判斷文件是否存在
        String originalContent = read(filePath);
        StringBuilder stringBuilder = new StringBuilder();
        if (originalContent != null) {
            if (originalContent.length() > 0) {
                stringBuilder.append(originalContent);
                stringBuilder.append("\n");
            }
            stringBuilder.append(content);
            write(filePath, stringBuilder.toString());
        } else {
            System.out.println("文件不存在");
        }
    }
}

python

python 中使用 with 语句进行资源释放控制,搭配 open 函数进行文件的读操作。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: RaoLong
# datetime: 2021/6/27 19:28 
# ide: PyCharm

class FileUtil:

    @staticmethod
    def read(filePath):
        try:
            with open(filePath, "r") as fp:
                content = fp.read()
            return content
        except FileNotFoundError:
            print(f"没有找到文件: '{filePath}'")
            return None

    @staticmethod
    def write(filePath, content):
        with open(filePath, "w") as fp:
            fp.write(content)

    @staticmethod
    def append(filePath, content):
        with open(filePath, "a") as fp:
            fp.write(content)

NodeJs

var fs = require('fs');

class FileUtil {
    static read(filePath) {
        fs.readFile(filePath, function (error, data) {
            if (error) {
                console.log(`读取文件失败: ${filePath}`)
            } else {
                console.log(data.toString());
            }
        });
    }

    static write(filePath, content) {
        fs.writeFile(filePath, content, function (error, data) {
            if (error) {
                console.log(`写入文件失败: ${filePath}`)
            } else {
                console.log(`写入文件成功: ${filePath}`)
            }
        });
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值