Getting Junk characters while trying to print the file contents using Java

Posted by user1523797 on Stack Overflow See other posts from Stack Overflow or by user1523797
Published on 2012-09-05T09:36:09Z Indexed on 2012/09/05 9:38 UTC
Read the original article Hit count: 154

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about readfile