Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Junk characters while reading text file in java

Tags:

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

like image 784
user2223335 Avatar asked Aug 31 '26 14:08

user2223335


1 Answers

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

like image 148
Juned Ahsan Avatar answered Sep 03 '26 04:09

Juned Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!