我正在读取文件的内容并尝试使用 java 打印内容。但它会与文件内容一起打印垃圾字符。
代码:
import java.io.*;
public class ReadFile {
public String readFile(String filePath){
StringBuilder contents = new StringBuilder();
File file = new File(filePath);
try{
String lines = null;
FileReader fileReader1 = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader1);
while((lines = buffer.readLine())!=null){
contents.append(lines);
}
buffer.close();
}
catch(FileNotFoundException ex){
System.out.println("File not found.");
}catch(IOException ex){
System.out.println("Exception ocurred.");
}
return contents.toString();
}
public static void main(String[] args){
ReadFile rf = new ReadFile();
String lines = rf.readFile("C:\\Data\\FaultDn.txt");
System.out.println("Original file contents: " + lines);
}
}
文件内容为:
partner.cisco.com:org-root/mac-pool-QA_MAC_Pool_5-Sep-2012_12:00
输出是:
"Original file contents: ÿþp ..." and then junk characters after every letter.
你能指出我在这段代码中缺少什么吗?