Java IO 读取文件中的乱码问题

个人认为不管是用字节流还是字符流,都可以轻松的进行文件读取。当然,它们对乱码问题的处理方式是不同的。

1. 字节流

/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			InputStream in = new BufferedInputStream(new FileInputStream("D:/temp/a.txt"));
			int c;			
			StringBuffer sb = new StringBuffer();
			while ((c = in.read())>0){
				sb.append((char)c);

			}			
			
			String response = new String(sb.toString().getBytes("iso-8859-1"), "gb2312");
			System.out.print(response);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 

	}

 处理方法:对读取到的文件内容进行字符编码转换

 

2. 字符流

/**
	 * Read file's content
	 * 
	 * @param fileAndPath String the file and path
	 * @return String the file's content
	 */
	public static String readFile (String fileAndPath) {
		String fileContent = "";
		File file = new File(fileAndPath);
		if (file.isFile() && file.exists()) {	
			try {			
			
				InputStreamReader in = new InputStreamReader(new FileInputStream(file), "gb2312");
				BufferedReader bf = new BufferedReader(in);			
				String temp;
				while ((temp=bf.readLine()) !=null) {
					fileContent += temp+"\n";
				}
				bf.close();
				in.close();				
				
			}catch (FileNotFoundException e) {				
				System.out.println("File not found");
				e.printStackTrace();
				
			} catch (IOException e) {
				System.out.println("Something wrong when reading file");
				e.printStackTrace();
			} 
		}			
	   
		return fileContent;
		
	} 

 

处理方法: 读取文件时,用字符流类InputStreamReader进行编码转换

 

3. Linux 平台下

暂时没有碰到这样的问题。但是据说在Linux平台下,用字符流读取会有乱码问题。

-----------------------------------------------------

项目中要求读取数据文件通过java程序导入数据库,数据文件是ANSI编码格式的,在windows环境中没有什么问题,windows会自动将编码转换成为gb2312的,但是在linux平台上由于多语言,使用InputStreamReader由字节码转换为字符码的时候会容易产生无法正确转换的乱码,解决方法为读取的时候采用iso-8859-1格式读取,在程序中再次转码。

   BufferedReader reader = new BufferedReader(new InputStreamReader(
     new FileInputStream(filename),"iso-8859-1"));

    String line = reader.readLine();

    line = new String("iso-8859-1","gb2312");

----------------------------------------------------

以后碰到的话在研究吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值