所以我有一个像这样的日志文件
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
<someTag>someDetail</someTag>
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
<someTag>someDetail</someTag>
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
这是我的代码来读取文件
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class DummyReadFile {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:/Hussi/logFile.log"));
while ((sCurrentLine = br.readLine()) != null) {
//System.out.println(sCurrentLine);
if(sCurrentLine.contains("<"))
{
System.out.println("==>>>"+sCurrentLine);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
但是在我的输出中我得到了
b l a h b l a h b l a h
< s o m e T a g >s o m e D e t a i l < / s o m e T a g >
b l a h b l a h b l a h
< s o m e T a g >s o m e D e t a i l < / s o m e T a g >
b l a h b l a h b l a h
< s o m e T a g >s o m e D e t a i l < / s o m e T a g >
字符之间的空格实际上是一些正方形
我该怎么做才能正确阅读文件
我是否必须提及,文件格式,类似的东西?
答案 0 :(得分:1)
您的文件似乎是UTF-16文本编码格式
我已更改了两行,现在程序运行正常。
FileInputStream fin = new FileInputStream("C:/temp/test3.txt");
br = new BufferedReader(new InputStreamReader(fin, "UTF-16LE"));
修改后的工作程序
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class DummyReadFile {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
FileInputStream fin = new FileInputStream("C:/temp/test3.txt");
br = new BufferedReader(new InputStreamReader(fin, "UTF-16LE"));
//br = new BufferedReader(new FileReader("C:/temp/test3.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
/*if(sCurrentLine.contains("<"))
{
System.out.println("==>>>"+sCurrentLine);
}*/
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}