Getting Junk characters while trying to print the file contents using Java
- by user1523797
I am reading a file's contents and trying to print the contents using java. But it prints junk characters along with the file content.
Code:
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);
}
}
The file contents are:
partner.cisco.com:org-root/mac-pool-QA_MAC_Pool_5-Sep-2012_12:00
The output is:
![Alt Output](C:\Users\safarhee\Desktop\Output.jpg)
Can you please point me to what I am missing in this code?