`
kingj
  • 浏览: 421224 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

同样的代码和数据文件,为什么在eclipse中运行和在控制台运行的结果不一样?

 
阅读更多

今天遇到一个很诡异的问题,同一样的代码和同一个数据文件,在eclipse或者其它ide中能正常运行,为什么在控制台确不能正确的运行?

 

代码很简单,就是从一个数据文件中读取一定的行数,然后处理这些行

代码如下

 

 

public static void main(String[] args) throws Exception {
		final String SEPERATOR = "\" \"";
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("d:/test11.log")));
		String line = null;
		int c = 0;
		while ((line = reader.readLine()) != null && c < 5000) {
			String[] infos = line.split(SEPERATOR);
			if (infos.length != 13) {
				System.out.println("infos.length size = " + infos.length);
				throw new Exception(String.format("报错行数(%d,%s)\n", c, line));
			}
			c++;
		}
	}
 

这个数据文件是UTF-8的编码格式,其中有一些数据中存在诸如"?"之类的乱码。此时eclipse中工程的编码设置为UTF-8,程序能够正常的运行,

但是诡异的事情在我将工程的编码设置为gbk后就发生了,代码不能正常运行了。难道代码在eclipse中运行时,eclipse会自动拦截并用当前工程的编码

过滤文件的IO读写吗?

 

后来将代码改成如下:

 

 

public static void main(String[] args) throws Exception {
		final String SEPERATOR = "\" \"";
		BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("d:/test11.log"),"UTF-8"));
		String line = null;
		String other=null;
		int c = 0;
		while ((line = reader.readLine()) != null && c < 5000) {
			other=new String(line.getBytes(),"UTF-8");
			String[] infos = other.split(SEPERATOR);
			if (infos.length != 13) {
				System.out.println("infos.length size = " + infos.length);
				throw new Exception(String.format("报错行数(%d,%s)\n", c, line));
			}
			c++;
		}
	}

 

 给输入流加上UTF-8编码后,程序在ide中和控制台都能正常运行了

 

此时,无论给工程的编码属性配置成utf-8或者gbk都没有问题了,最让人费解的是elipse真的对IO流过滤了吗?

有谁知道这个问题请不吝赐教

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics