Java读写txt文件时防止中文乱码问题出现的方法介绍
作者:WOOSHN 时间:2023-06-23 04:40:32
问题:在用Java程序进行读写含中文的txt文件时,经常会出现读出或写入的内容会出现乱码。原因其实很简单,就是系统的编码和程序的编码采用了不同的编码格式。通常,假如自己不修改的话,windows自身采用的编码格式是gbk(而gbk和gb2312基本上是一样的编码方式),而IDE中Encode不修改的话,默认是utf-8的编码,这就是为什么会出现乱码的原因。当在OS下手工创建并写入的txt文件(gbk),用程序直接去读(utf-8),就会乱码。为了避免可能的中文乱码问题,最好在文件写入和读出的时候显式指定编码格式。
1、写文件:
public static void writeFile(String fileName, String fileContent)
{
try
{
File f = new File(fileName);
if (!f.exists())
{
f.createNewFile();
}
OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f),"gbk");
BufferedWriter writer=new BufferedWriter(write);
writer.write(fileContent);
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
2、读文件:
public static String readFile(String fileName)
{
String fileContent = "";
try
{
File f = new File(fileName);
if(f.isFile()&&f.exists())
{
InputStreamReader read = new InputStreamReader(new FileInputStream(f),"gbk");
BufferedReader reader=new BufferedReader(read);
String line;
while ((line = reader.readLine()) != null)
{
fileContent += line;
}
read.close();
}
} catch (Exception e)
{
e.printStackTrace();
}
return fileContent;
}
标签:Java,txt
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java设计模式之建造者模式的示例详解
2022-02-13 18:47:34
![](https://img.aspxhome.com/file/2023/2/82452_0s.jpg)
java报错:找不到或无法加载主类的解决方法简单粗暴
2023-03-29 17:20:58
![](https://img.aspxhome.com/file/2023/4/93074_0s.png)
android开发之Json文件的读写的示例代码
2021-12-02 11:55:18
![](https://img.aspxhome.com/file/2023/2/84712_0s.png)
详解Java如何实现在PDF中插入,替换或删除图像
2022-04-07 22:40:36
![](https://img.aspxhome.com/file/2023/4/80864_0s.jpg)
C语言字符串操作总结大全(超详细)
2023-07-06 15:14:56
浅谈Java中向上造型向下造型和接口回调中的问题
2023-11-09 13:51:46
![](https://img.aspxhome.com/file/2023/1/59151_0s.jpg)
maven依赖版本没有按照最短路径原则生效的解决方案
2023-04-04 20:49:09
Gradle:修改默认的Build配置文件名方式
2023-11-28 20:18:01
![](https://img.aspxhome.com/file/2023/7/60617_0s.png)
深入理解Java设计模式之建造者模式
2022-12-06 00:57:37
![](https://img.aspxhome.com/file/2023/8/94218_0s.jpg)
spring boot加载第三方jar包的配置文件的方法
2023-03-02 22:45:13
C#常用目录文件操作类实例
2023-06-24 13:30:24
C#创建WebService接口并连接的全过程
2023-04-07 07:47:21
![](https://img.aspxhome.com/file/2023/5/100085_0s.jpg)
基于WPF实现控件轮廓跑马灯动画效果
2022-05-03 20:10:08
![](https://img.aspxhome.com/file/2023/6/92976_0s.png)
C#实现SMTP邮件附件发送功能详解
2022-08-14 10:09:38
![](https://img.aspxhome.com/file/2023/9/89829_0s.png)
Unity 制作一个分数统计系统
2021-11-30 03:01:52
![](https://img.aspxhome.com/file/2023/7/106377_0s.gif)
Android蓝牙通信聊天实现发送和接受功能
2022-02-07 21:58:56
Java创建树形结构算法实例代码
2021-11-21 22:24:01
JVM常量池的深入讲解
2021-09-13 15:54:00
![](https://img.aspxhome.com/file/2023/8/66468_0s.png)
Java的idea连接mongodb数据库的详细教程
2023-11-19 08:07:58
![](https://img.aspxhome.com/file/2023/1/59711_0s.png)
c#方法重写和隐藏的学习示例
2022-12-24 14:20:12