我在阅读与URL连接的文本形式InputStream时遇到问题。 我正在使用Scanner来阅读文本,但看起来没有文本格式化。
这是代码
connection = new URL(finalURL).openConnection();
connection.connect();
inStream = connection.getInputStream();
in = new Scanner(inStream);
while(in.hasNextLine()){
line = in.nextLine();
System.out.println(line);
}
connection = new URL(finalURL).openConnection();
connection.connect();
inStream = connection.getInputStream();
in = new Scanner(inStream);
while(in.hasNextLine()){
line = in.nextLine();
System.out.println(line);
}
我省略了try catch子句。
输出是这样的:
μtÂ÷BPv§2d
ŐüUŘ}ĎÓăR
虽然它应该是这样的:
06MAGNA,20121109,0.26,0.27,0.25,0.27,37820
08OCTAVA,20121109,0.73,0.75,0.73,0.73,12244
当我将它作为txt文件保存在磁盘上然后使用Scanner时,它工作正常但通过URL却没有。谁能帮我?
答案 0 :(得分:1)
我认为它的发生是因为输入流和扫描仪的默认字符集中的charset不同。尝试在Charset
构造函数中传递Scanner
。
in = new Scanner(inStream, "UTF-8");//set the appropriate charset
编辑:您可以使用connection.getContentEncoding()
获取内容编码。
将扫描仪实例化更新为:
in = new Scanner(inStream, connection.getContentEncoding());
EDIT1 :要处理gzip
输入流,请使用GZIPInputStream
,如下所示:
inputStream = new GZIPInputStream(connection.getInputStream());