I'm reading in a file and replacing some text, then writing a new file, line by line. I use the following code to read and write the file. Usually there are no issues with files that are CP1252 and UTF-8 encoded, but when I try reading in a file that is encoded in "UCS-2 LE BOM" the file that is saved starts with BOM characters and contains whole lot of whitespace. I know that this is due to the encoding but I don't know if I need to read it in differently or save it differently. Also, I know I could set the encoding when I read the file in, but how can I handle differntly-encoded files without knowing which one is coming. I have no control over the file until it hits my java code. Any help is appreciated, thank you.
FileInputStream sourceFileInputStream = new FileInputStream(sourceFile);
DataInputStream sourceDataInputStream = new DataInputStream(sourceFileInputStream);
BufferedReader sourceBufferedReader = new BufferedReader(
new InputStreamReader(sourceDataInputStream));
FileWriter targetFileWriter = new FileWriter(new File(targetFileLocation));
BufferedWriter targetBufferedWriter = new BufferedWriter(
targetFileWriter);
.
.
.
targetBufferedWriter.write(newTextline);