用了下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
发现中文都乱码了,请问如何解决?
测试代码如下:
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
我还试了
System.out.println(new String(new String(line.getBytes("ISO8859-1").getBytes("UTF-8"),"GBK"));
System.out.println(new String(line.getBytes("ISO8859-1"),"GBK"));
都没用
中文或其他国语言的字符,它不会解码的。
所以,我不太建议楼主用这个类。我给楼主做了一个简单的手动解码,楼主可以根据文件的编码,更改设置。
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);
}
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);
}