日期:2014-05-20  浏览次数:20787 次

java库的中文乱码问题求助Orz
用了下org.apache.commons.io.input.Tailer
发现中文都乱码了,请问如何解决?
测试代码如下:
package test;

import java.io.File;

import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;

public class TestTailer {
public static void main(String[] args) throws InterruptedException {
TailerListener listener = new TestTailListener();
Tailer tailer = new Tailer(new File("E:\\a.txt"), listener);
Thread thread = new Thread(tailer);
thread.setDaemon(true); // optional
thread.start();
thread.sleep(1000);
}
}



package test;

import java.io.UnsupportedEncodingException;

import org.apache.commons.io.input.TailerListenerAdapter;

public class TestTailListener extends TailerListenerAdapter {
public void handle(String line) {

try {
System.out.println(new String(line.getBytes("ISO8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

}



测试文件名a.txt 放在E:\\a.txt 里面内容是:

test
测试中文
test over

------解决方案--------------------
哦。忘了打印line对象的内容了。
	public void handle(String line) {
final Charset charset = Charset.defaultCharset();//Charset.forName("UTF-8");
char[] chs = line.toCharArray();
byte[] data = new byte[chs.length];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) chs[i];
}
line = new String(data,charset);
System.out.println(line);
}