一、写文件
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
/**
* @author chenwc
* @date 2024/4/1 22:23
*/
public class WriteFile {
private static final Logger log = LoggerFactory.getLogger(WriteFile.class);
/**
* 流交换操作,把流写入到文件
*
* @param ins 输入流
* @param tarFile 待写入文件
*/
private static void transferStream(InputStream ins, File tarFile) {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 10);
ReadableByteChannel rbcInst = Channels.newChannel(ins);
//获取目标输出文件的fileChannel
FileChannel fileChannel = null;
FileOutputStream fos = null;
log.info("写入文件路径: {}", tarFile.getAbsolutePath());
try {
if (!tarFile.exists()) {
mkdirParents(tarFile);
if (!tarFile.createNewFile()) {
log.info("文件不存在,创建文件失败!");
return;
} else {
log.info("文件不存在,创建文件成功!");
}
}
long start = System.currentTimeMillis();
log.info("开始写入文件............");
fos = new FileOutputStream(tarFile);
fileChannel = fos.getChannel();
while (-1 != (rbcInst.read(byteBuffer))) {
byteBuffer.flip();
fileChannel.write(byteBuffer);
byteBuffer.clear();
}
long end = System.currentTimeMillis();
log.info("写入文件成功............");
log.info("写入文件耗时: {} ms", end - start);
} catch (IOException ioe) {
log.error("Error occurred: ", ioe);
} finally {
try {
if (null != fos) {
fos.close();
}
if (null != rbcInst) {
rbcInst.close();
}
if (null != fileChannel) {
fileChannel.close();
}
} catch (IOException e) {
log.error("Error occurred: ", e);
}
}
}
/**
* 以UTF-8字符编码格式写入文本内容到文件(字符流)
*
* @param content 待写入文本内容
* @param path 文件路径+文件名
*/
public static void writeFileByWriter(String content, String path) {
writeFileByWriter(content, path, StandardCharsets.UTF_8, false);
}
/**
* 以UTF-8字符编码格式写入文本内容到文件(字符流)
*
* @param content 待写入文本内容
* @param path 文件路径+文件名
* @param isAppend 是否把把数据追加写入文件
*/
public static void writeFileByWriter(String content, String path, boolean isAppend) {
writeFileByWriter(content, path, StandardCharsets.UTF_8, isAppend);
}
/**
* 以指定字符编码格式写入文本内容到文件(字符流)
*
* @param content 待写入文本内容
* @param path 文件路径+文件名
* @param charset 待写入文件的字符编码
* @param isAppend 是否把把数据追加写入文件
*/
public static void writeFileByWriter(String content, String path, Charset charset, boolean isAppend) {
Writer writer = null;
File file = new File(path);
log.info("写入文件路径: {}", file.getAbsolutePath());
try {
if (!file.exists()) {
mkdirParents(file);
if (!file.createNewFile()) {
log.info("文件不存在,创建文件失败!");
return;
} else {
log.info("文件不存在,创建文件成功!");
}
}
long start = System.currentTimeMillis();
log.info("开始写入文件............");
if (isAppend) {
writer = new OutputStreamWriter(new FileOutputStream(file, true), charset);
} else {
writer = new OutputStreamWriter(new FileOutputStream(file, false), charset);
}
writer.write(content);
long end = System.currentTimeMillis();
log.info("写入文件成功............");
log.info("写入文件耗时: {} ms", end - start);
} catch (IOException e) {
// TODO 自动生成的 catch 块
log.error("Error occurred: ", e);
} finally {
try {
if (null != writer) {
writer.close();
}
} catch (Exception e2) {
// TODO: handle exception
log.error("Error occurred: ", e2);
}
}
}
/**
* 通过 FileOutputStream 写入文件(字节流)
*
* @param bytes 待写入文件的二进制内容
* @param path 文件路径+文件名
*/
public static void writeFileByFileOutputStream(byte[] bytes, String path) {
FileOutputStream fileOutputStream = null;
File file = new File(path);
log.info("写入文件路径: {}", file.getAbsolutePath());
try {
if (!file.exists()) {
mkdirParents(file);
if (!file.createNewFile()) {
log.info("文件不存在,创建文件失败!");
return;
} else {
log.info("文件不存在,创建文件成功!");
}
}
long start = System.currentTimeMillis();
log.info("开始写入文件............");
fileOutputStream = new FileOutputStream(file, false);
fileOutputStream.write(bytes);
long end = System.currentTimeMillis();
log.info("写入文件成功............");
log.info("写入文件耗时: {} ms", end - start);
} catch (Exception e) {
log.error("Error occurred: ", e);
} finally {
try {
if (null != fileOutputStream) {
fileOutputStream.close();
}
} catch (Exception e2) {
// TODO: handle exception
log.error("Error occurred: ", e2);
}
}
}
/**
* 把 InputStream 流写入本地文件(字节流)
*
* @param inputStream InputStream 流
* @param filePath 待写入本地文件全路径+文件名
*/
public static void writeFileByInputStream(InputStream inputStream, String filePath) {
File file = new File(filePath);
log.info("写入文件路径: {}", file.getAbsolutePath());
OutputStream outputStream = null;
try {
if (!file.exists()) {
mkdirParents(file);
if (!file.createNewFile()) {
log.info("文件不存在,创建文件失败!");
return;
} else {
log.info("文件不存在,创建文件成功!");
}
}
long start = System.currentTimeMillis();
log.info("开始写入文件............");
outputStream = new BufferedOutputStream(Files.newOutputStream(file.toPath()));
byte[] buffer = new byte[1024 * 10];
int bytesRead;
while ((bytesRead = readNBytes(inputStream, buffer, 0, buffer.length)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
long end = System.currentTimeMillis();
log.info("写入文件成功............");
log.info("写入文件耗时: {} ms", end - start);
} catch (IOException e) {
log.error("Error occurred: ", e);
} finally {
try {
if (null != inputStream) {
inputStream.close();
}
if (null != outputStream) {
//保存数据
outputStream.close();
}
} catch (IOException e) {
log.error("Error occurred: ", e);
}
}
}
/**
* 读取 InputStream 流中的数据
*
* @param inputStream InputStream 流
* @param b 待读取的二进制数组
* @param off 读取的起始位置
* @param len 读取的长度
* @return 读取到的字节数
* @throws IOException IO异常
*/
public static int readNBytes(InputStream inputStream, byte[] b, int off, int len) throws IOException {
int n;
int count;
for (n = 0; n < len; n += count) {
count = inputStream.read(b, off + n, len - n);
if (count < 0) {
break;
}
}
return n;
}
/**
* 判断文件的父级目录是否存在,不存在则创建
*
* @param file 文件
* @return true 父级目录存在或创建父级目录成功, false创建父级目录失败
*/
private static boolean mkdirParents(File file) {
if (!file.getParentFile().exists()) {
return file.getParentFile().mkdirs();
} else {
return true;
}
}
}
二、读文件
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
/**
* @author chenwc
* @date 2024/4/1 22:23
*/
public class ReadFile {
private static final Logger log = LoggerFactory.getLogger(ReadFile.class);
/**
* 以UTF-8字符编码读取文本文件内容(字符流)
*
* @param path 文件路径
* @return 文件内容
*/
public static String readFileByInputStreamReader(String path) {
return readFileByInputStreamReader(path, StandardCharsets.UTF_8);
}
/**
* 以指定字符编码读取文本文件内容(字符流)
*
* @param path 文件路径
* @param charset 读取文件使用的字符编码
* @return 文件内容
*/
public static String readFileByInputStreamReader(String path, Charset charset) {
File file = new File(path);
log.info("读取文件路径: {}", file.getAbsolutePath());
InputStreamReader inputStreamReader = null;
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
if (!file.exists()) {
log.info("文件不存在,读取文件失败!");
return null;
}
long start = System.currentTimeMillis();
log.info("开始读取文件............");
inputStreamReader = new InputStreamReader(Files.newInputStream(file.toPath()), charset);
br = new BufferedReader(inputStreamReader);
String string;
//按行读取文件
while ((string = br.readLine()) != null) {
sb.append(string).append("\r\n");
}
long end = System.currentTimeMillis();
log.info("读取文件成功............");
log.info("读取文件耗时: {} ms", end - start);
} catch (Exception e) {
// TODO: handle exception
log.error("Error occurred: ", e);
} finally {
try {
if (null != br) {
br.close();
}
if (null != inputStreamReader) {
inputStreamReader.close();
}
} catch (Exception e2) {
// TODO: handle exception
log.error("Error occurred: ", e2);
}
}
return sb.toString();
}
/**
* 通过 FileInputStream 读取文件内容(字节流),最大读取文件大小为 Integer.MAX_VALUE (B)
*
* @param fis FileInputStream
* @param fileLength 文件大小
* @return 二进制文件内容
*/
public static byte[] readFileByInputStream(FileInputStream fis, long fileLength) {
byte[] result = new byte[(int) fileLength];
try {
long start = System.currentTimeMillis();
log.info("开始读取文件............");
int available = fis.available();
log.info("available: {}", available);
if (available <= 0) {
log.info("待读取文件为空文件,读取文件失败");
return null;
}
byte[] buffer = new byte[1024 * 10];
int bytesRead;
int startIndex = 0;
while ((bytesRead = readNBytes(fis, buffer, 0, buffer.length)) > 0) {
//src 源数组,srcPos 从源数组哪个位置开始拷贝,dest 目标数组,destPos 从目标数组哪个位置开始复制,length 复制多少长度
System.arraycopy(buffer, 0, result, startIndex, bytesRead);
startIndex += bytesRead;
}
long end = System.currentTimeMillis();
log.info("读取文件成功............");
log.info("读取文件耗时: {} ms", end - start);
} catch (Exception e) {
log.error("Error occurred: ", e);
} finally {
// 在finally语句块当中确保流一定关闭。
try {
if (null != fis) {
fis.close();
}
} catch (Exception e2) {
// TODO: handle exception
log.error("Error occurred: ", e2);
}
}
return result;
}
/**
* 读取 InputStream 流中的数据
*
* @param inputStream InputStream 流
* @param b 待读取的二进制数组
* @param off 读取的起始位置
* @param len 读取的长度
* @return 读取到的字节数
* @throws IOException IO异常
*/
public static int readNBytes(InputStream inputStream, byte[] b, int off, int len) throws IOException {
int n;
int count;
for (n = 0; n < len; n += count) {
count = inputStream.read(b, off + n, len - n);
if (count < 0) {
break;
}
}
return n;
}
/**
* 通过 FileInputStream 读取文件内容(字节流),最大读取文件大小为 Integer.MAX_VALUE (B)
*
* @param path 文件路径
* @return 二进制文件内容
*/
public static byte[] readFileByFileInputStream(String path) {
File file = new File(path);
log.info("读取文件路径: {}", file.getAbsolutePath());
byte[] result = null;
try {
if (!file.exists()) {
log.info("文件不存在,读取文件失败!");
return null;
}
result = readFileByInputStream(new FileInputStream(file), file.length());
} catch (Exception e) {
log.error("Error occurred: ", e);
}
return result;
}
}
三、测试
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.chenwc.read.ReadFile;
import com.chenwc.write.WriteFile;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
// TODO 自动生成的方法存根
File pathFile = new File("1.txt");
//当前根目录下
String path = pathFile.getAbsolutePath().replace("1.txt", "");
String content = String.valueOf(System.nanoTime());
path = path + "\\file\\测试写入.txt";
//WriteFile.writeFileByWriter(content, path);
for (int i = 0; i < 100; i++) {
content = String.valueOf(System.nanoTime()) + "\r\n";
WriteFile.writeFileByWriter(content, path, true);
}
byte[] result = ReadFile.readFileByFileInputStream(path);
String resultString = new String(result, StandardCharsets.UTF_8);
log.info("读取到的内容长度为: {}", String.valueOf(resultString.getBytes(StandardCharsets.UTF_8).length));
String readFilePathString = "D:\\Desktop\\新建文件夹\\测试.xlsx";
result = ReadFile.readFileByFileInputStream(readFilePathString);
WriteFile.writeFileByFileOutputStream(result, "D:\\Downloads\\新写出文件.xlsx");
}
}