假如你要設置的編碼形式都是UTF-8 ,出現亂碼問題如下:
1.txt文件的編碼形式不是UTF-8,詳細操作見鏈接:
https://zhidao.baidu.com/question/560895811224581924.html
2.eclipse中編碼方式不是UTF-8,詳細操作見鏈接:
https://jingyan.baidu.com/article/2009576193ee38cb0721b416.html
3.mysql中的編碼方式默認是拉丁文,得改
注意:我的mysql是5.7版本的
具體操作:
(1)進入my.ini所在的目錄:C:\ProgramData\MySQL\MySQL Server 5.7
(2)修改my.ini文件,只要[client]下面一行添加default-character-set=utf8和[mysqld]下面一行添加character_set_server=utf8即可, 得慢慢找。。。 下面只給出關鍵的部分
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]
default-character-set=utf8
# pipe=
# socket=MYSQL
port=3306
[mysql]
no-beep
# default-character-set=
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
# server_type=3
[mysqld]
character_set_server=utf8
說明:之前有人直接用set命令修改mysql字符集編碼方式,但是那樣並不是永久有效!!!重啓mysql後還是默認編碼方式拉丁語,所以得修改my.ini文件才能永久有效。
(3)字符集查看:
保存後重啓服務器,登陸後在命令行輸入:show variables like 'char%';
修改後默認字符集如下圖所示:說明修改成功
4.eclipse代碼裏面沒有轉碼,Reader reader = new InputStreamReader(new FileInputStream(srcFile), "UTF-8");
少了這句也不行,最近剛學,也不太懂,漏了這句也會是亂碼。
我的目標文件是itcast.txt,放在d盤根目錄下。輸出是爲了做測試。
package cn.itcast.jdbc.example.domain;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class demo {
public static void main(String[] args) {
// 1.定義目標文件
File srcFile = new File("D:/itcast.txt");
try {
@SuppressWarnings("resource")
//2.讀取文件
Reader reader = new InputStreamReader(new FileInputStream(srcFile), "UTF-8");
// 3.循環往外流
int content = reader.read();
// 4.循環打印
while (content != -1) {
System.out.print((char) content);
content = reader.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}