前言
这个是方便自己用才写的博客,没有什么技术含量,如果帮助你了很高兴。
内容部分参考:https://blog.csdn.net/qq_36868342/article/details/76577758
PS:如果你使用时依旧存在乱码情况,请为读取和写入的txt文件设置编码模式,保证文件编码一致并和代码读写的编码相同(txt文件内ANSI相当于GBK编码)。设置编码代码:new InputStreamReader(new FileInputStream(file),“utf-8”)。
代码内容
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
public class Test {
public static void main(String[] args) {
// 使用高层流读取文件
File file = new File("D:/test/Response.txt");
File outFile = new File("D:/test/test.txt");
Reader reader = null;
Writer writer = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
// 构造基础流
reader = new InputStreamReader(new FileInputStream(file),"utf-8");
writer = new OutputStreamWriter(new FileOutputStream(outFile),"utf-8");
// 在基础流之上构造高层流
br = new BufferedReader(reader);
bw = new BufferedWriter(writer);
// 读到的一行
String line = null;
while ((line = br.readLine()) != null) {
// System.out.println("读到: " + line);
bw .write(line + "\r\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 先关闭高层流
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (bw != null) {
try {
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 关闭基础流
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
字节数组和文件
/**
* 将文件转换为字节数组
* @param filePath
* @return
*/
private static byte[] fileToByteArray(String filePath) {
File file = new File(filePath);
//流定义在try中不需要手动释放
try(InputStream is = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();) {
byte[] flush = new byte[1024 * 10];
int len = -1;
while ((len = is.read(flush)) != -1) {
baos.write(flush, 0, len);
}
baos.flush();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 字节数组输出到文件
* @param src
* @param filePath
*/
private static void byteArrayToFile(byte[] src, String filePath) {
File file = new File(filePath);
BufferedOutputStream os = null;
ByteArrayInputStream bais = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
bais = new ByteArrayInputStream(src);
byte[] flush = new byte[1024 * 10];
int len = -1;
while ((len = bais.read(flush)) != -1) {
os.write(flush, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}