eclipse 使用IO流读取txt文件并传入到mysql中,出现乱码问题

假如你要设置的编码形式都是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();
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章