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}`)
}
});
}
}