user2223335
user2223335

Reputation: 209

Junk characters while reading text file in java

I have a java which calls windows bat file which does some processing and generates the output file.
Process p = Runtime.getRuntime().exec("cmd /c "+filename);
Now when reading the file from following program. (filexists() is function which checks whether file exists or not). Output file contains only single line

if ( filexists("output.txt") == true)    
{   String FileLine; 
    FileInputStream fstream = new FileInputStream("output.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

    FileLine = br.readLine();
    fstream.close();
    filein.close();

}

Variable FileLine contains 3 junk charcters in the starting. I also checked few other files in the progam and no file has this issue except for the fact it is created with Runtime function.
9087.
As you can see three junk characters are coming in the output file. When opened with Notepad++, i am not able to see those junk characters.

Please suggest

Upvotes: 3

Views: 4669

Answers (3)

Saurabh
Saurabh

Reputation: 7964

May be its an issue with file encoding. Though I am not sure. Can you please try following piece of code and see if it works for you

BufferedReader in = new BufferedReader(
new InputStreamReader( new FileInputStream("output.txt"), "UTF8"));

String str;

while ((str = in.readLine()) != null) {
  System.out.println(str);
}

Upvotes: 1

SimonC
SimonC

Reputation: 6718

That looks like the byte order mark for UTF-8 encoding. See https://en.wikipedia.org/wiki/Byte_order_mark

Upvotes: 5

Juned Ahsan
Juned Ahsan

Reputation: 68715

This is happening because you have not mentioned the file encoding while creating your FileInputStream.Assuming your file is UTF-8 encoded, you need to do something like this

   new FileInputStream("output.txt, "UTF-8"));

Change the encoding as per the encoding of your file

Upvotes: 6

Related Questions