Java读取、写入文件如何解决乱码问题
来源:互联网 发布:war3 mac 版本转换器 编辑:程序博客网 时间:2024/05/20 09:45
读取文件流时,经常会遇到乱码的现象,造成乱码的原因当然不可能是一个,这里主要介绍因为文件编码格式而导致的乱码的问题。首先,明确一点,文本文件与二进制文件的概念与差异。
文本文件是基于字符编码的文件,常见的编码有ASCII编码,UNICODE编码、ANSI编码等等。二进制文件是基于值编码的文件,你可以根据具体应用,指定某个值是什么意思(这样一个过程,可以看作是自定义编码。)
因此可以看出文本文件基本上是定长编码的(也有非定长的编码如UTF-8)。而二进制文件可看成是变长编码的,因为是值编码嘛,多少个比特代表一个值,完全由你决定。
对于二进制文件,是千万不能使用字符串的,因为字符串默认初始化时会使用系统默认编码,然而,二进制文件因为自定义编码自然与固定格式的编码会有所冲突,所以对于二进制的文件只能采用字节流读取、操作、写入。
对于文本文件,因为编码固定,所以只要在读取文件之前,采用文件自身的编码格式解析文件,然后获取字节,再然后,通过指定格式初始化字符串,那么得到的文本是不会乱码的。虽然,二进制文件也可以获取到它的文本编码格式,但是那是不准确的,所以不能同日而语。
具体操作如下:
1)获取文本文件的格式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public
static
String getFileEncode(String path) {
String charset =
"asci"
;
byte
[] first3Bytes =
new
byte
[
3
];
BufferedInputStream bis =
null
;
try
{
boolean
checked =
false
;
bis =
new
BufferedInputStream(
new
FileInputStream(path));
bis.mark(
0
);
int
read = bis.read(first3Bytes,
0
,
3
);
if
(read == -
1
)
return
charset;
if
(first3Bytes[
0
] == (
byte
)
0xFF
&& first3Bytes[
1
] == (
byte
)
0xFE
) {
charset =
"Unicode"
;
//UTF-16LE
checked =
true
;
}
else
if
(first3Bytes[
0
] == (
byte
)
0xFE
&& first3Bytes[
1
] == (
byte
)
0xFF
) {
charset =
"Unicode"
;
//UTF-16BE
checked =
true
;
}
else
if
(first3Bytes[
0
] == (
byte
)
0xEF
&& first3Bytes[
1
] == (
byte
)
0xBB
&& first3Bytes[
2
] == (
byte
)
0xBF
) {
charset =
"UTF8"
;
checked =
true
;
}
bis.reset();
if
(!checked) {
int
len =
0
;
int
loc =
0
;
while
((read = bis.read()) != -
1
) {
loc++;
if
(read >=
0xF0
)
break
;
if
(
0x80
<= read && read <=
0xBF
)
//单独出现BF以下的,也算是GBK
break
;
if
(
0xC0
<= read && read <=
0xDF
) {
read = bis.read();
if
(
0x80
<= read && read <=
0xBF
)
//双字节 (0xC0 - 0xDF) (0x80 - 0xBF),也可能在GB编码内
continue
;
else
break
;
}
else
if
(
0xE0
<= read && read <=
0xEF
) {
//也有可能出错,但是几率较小
read = bis.read();
if
(
0x80
<= read && read <=
0xBF
) {
read = bis.read();
if
(
0x80
<= read && read <=
0xBF
) {
charset =
"UTF-8"
;
break
;
}
else
break
;
}
else
break
;
}
}
//TextLogger.getLogger().info(loc + " " + Integer.toHexString(read));
}
}
catch
(Exception e) {
e.printStackTrace();
}
finally
{
if
(bis !=
null
) {
try
{
bis.close();
}
catch
(IOException ex) {
}
}
}
return
charset;
}
private
static
String getEncode(
int
flag1,
int
flag2,
int
flag3) {
String encode=
""
;
// txt文件的开头会多出几个字节,分别是FF、FE(Unicode),
// FE、FF(Unicode big endian),EF、BB、BF(UTF-8)
if
(flag1 ==
255
&& flag2 ==
254
) {
encode=
"Unicode"
;
}
else
if
(flag1 ==
254
&& flag2 ==
255
) {
encode=
"UTF-16"
;
}
else
if
(flag1 ==
239
&& flag2 ==
187
&& flag3 ==
191
) {
encode=
"UTF8"
;
}
else
{
encode=
"asci"
;
// ASCII码
}
return
encode;
}
2)通过文件的编码格式读取文件流
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 通过路径获取文件的内容,这个方法因为用到了字符串作为载体,为了正确读取文件(不乱码),只能读取文本文件,安全方法!
*/
public
static
String readFile(String path){
String data =
null
;
// 判断文件是否存在
File file =
new
File(path);
if
(!file.exists()){
return
data;
}
// 获取文件编码格式
String code = FileEncode.getFileEncode(path);
InputStreamReader isr =
null
;
try
{
// 根据编码格式解析文件
if
(
"asci"
.equals(code)){
// 这里采用GBK编码,而不用环境编码格式,因为环境默认编码不等于操作系统编码
// code = System.getProperty("file.encoding");
code =
"GBK"
;
}
isr =
new
InputStreamReader(
new
FileInputStream(file),code);
// 读取文件内容
int
length = -
1
;
char
[] buffer =
new
char
[
1024
];
StringBuffer sb =
new
StringBuffer();
while
((length = isr.read(buffer,
0
,
1024
) ) != -
1
){
sb.append(buffer,
0
,length);
}
data =
new
String(sb);
}
catch
(Exception e){
e.printStackTrace();
log.info(
"getFile IO Exception:"
+e.getMessage());
}
finally
{
try
{
if
(isr !=
null
){
isr.close();
}
}
catch
(IOException e) {
e.printStackTrace();
log.info(
"getFile IO Exception:"
+e.getMessage());
}
}
return
data;
}
3)通过文件指定的格式写入文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 按照指定的路径和编码格式保存文件内容,这个方法因为用到了字符串作为载体,为了正确写入文件(不乱码),只能写入文本内容,安全方法
*
* @param data
* 将要写入到文件中的字节数据
* @param path
* 文件路径,包含文件名
* @return boolean
* 当写入完毕时返回true;
*/
public
static
boolean
writeFile(
byte
data[], String path , String code){
boolean
flag =
true
;
OutputStreamWriter osw =
null
;
try
{
File file =
new
File(path);
if
(!file.exists()){
file =
new
File(file.getParent());
if
(!file.exists()){
file.mkdirs();
}
}
if
(
"asci"
.equals(code)){
code =
"GBK"
;
}
osw =
new
OutputStreamWriter(
new
FileOutputStream(path),code);
osw.write(
new
String(data,code));
osw.flush();
}
catch
(Exception e){
e.printStackTrace();
log.info(
"toFile IO Exception:"
+e.getMessage());
flag =
false
;
}
finally
{
try
{
if
(osw !=
null
){
osw.close();
}
}
catch
(IOException e){
e.printStackTrace();
log.info(
"toFile IO Exception:"
+e.getMessage());
flag =
false
;
}
}
return
flag;
}
4)对于二进制文件而且内容很少的,例如Word文档等,可以使用如下方式读取、写入文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 从指定路径读取文件到字节数组中,对于一些非文本格式的内容可以选用这个方法
* 457364578634785634534
* @param path
* 文件路径,包含文件名
* @return byte[]
* 文件字节数组
*
*/
public
static
byte
[] getFile(String path)
throws
IOException {
FileInputStream stream=
new
FileInputStream(path);
int
size=stream.available();
byte
data[]=
new
byte
[size];
stream.read(data);
stream.close();
stream=
null
;
return
data;
}
/**
* 把字节内容写入到对应的文件,对于一些非文本的文件可以采用这个方法。
* @param data
* 将要写入到文件中的字节数据
* @param path
* 文件路径,包含文件名
* @return boolean isOK 当写入完毕时返回true;
* @throws Exception
*/
public
static
boolean
toFile(
byte
data[], String path)
throws
Exception {
FileOutputStream out=
new
FileOutputStream(path);
out.write(data);
out.flush();
out.close();
out=
null
;
return
true
;
}
阅读全文
0 0
- Java读取、写入文件如何解决乱码问题
- Java中按照行读取和写入文件 日志常用操作 解决中文乱码问题
- Java IO 读取/写入文件 中文乱码困难解决代码
- Java读取文件 解决中文乱码问题
- 解决php读取/写入mssql乱码问题
- Java 读取写入文件乱码问题解决
- 解决读取文件乱码问题
- 解决java写入Access乱码问题
- Java读取properties文件中文乱码问题的解决
- 解决 JAVA读取本地ANSI文件乱码问题
- 解决Java读取properties文件中文乱码的问题
- JAVA本地读取文件,解决中文乱码问题
- 解决PHP写入、读取MYSQL数据库数据中文乱码问题
- java 文件读取写入的编码问题
- 解决读取文件乱码问题小结
- 解决FileInputStream 读取文件中文乱码问题
- 解决python读取中文文件乱码问题
- 解决IO流读取文件乱码问题
- 使用XtraBackup只需6步即可创建Slave
- 史上最全Vim快捷键键位图(入门到进阶)
- Perl 中关于 LWP::UserAgent等模块用法
- java中的ArrayList 、List、LinkedList、Collection关系详解
- uefi 如何读写磁盘
- Java读取、写入文件如何解决乱码问题
- iOS 不同版本调用系统拨打电话使用不同的方法,避免调用卡顿甚至奔溃。
- 统计学习方法笔记三----逻辑斯蒂
- mybatis入门学习
- Android6.0 项目是512M以下的低内存设备,为什么没有多用户选项?
- 简析全双工与半双工的区别
- delphi2007+win10 "c:\Windows\Microsft.NET...\Borland.Delphi.Targets" was not found
- 结构体字节对齐,pragma pack,__attribute__(packed)
- 原生js轮播图