I am trying to read a file in as either UTF-8 or Windows-1252 depending on the output of this method:
public Charset getCorrectCharsetToApply() {
// Returns a Charset for either UTF-8 or Windows-1252.
}
So far, I have:
String fileName = getFileNameToReadFromUserInput();
InputStream is = new ByteArrayInputStream(fileName.getBytes());
InputStreamReader isr = new InputStreamReader(is, getCorrectCharsetToApply());
BufferedReader buffReader = new BufferedReader(isr);
The problem I'm having is converting the BufferedReader
instance to a FileReader
.
Furthermore:
fileName
) cannot be trusted to be a particular Charset
; sometime the file name will contain UTF-8 characters, and sometimes Windows-1252. Same goes for the file's content (however if file name and file content will always have matching charsets).getCorrectCharsetToApply()
can select the charset to apply, so attempting to read a file by its name prior to calling this method could very well result with, Java trying to read the file name with the wrong encoding...which causes it to die!Thanks in advance!
There are several ways to read a plain text file in Java e.g. you can use FileReader, BufferedReader, or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of data for fast reading, and Scanner provides parsing ability.
The native character encoding of the Java programming language is UTF-16.
When encoding a String, the following rules apply: The alphanumeric characters "a" through "z", "A" through "Z" and "0" through "9" remain the same. The special characters ".", "-", "*", and "_" remain the same. The blank space character " " is converted into a plus sign "+".
So, first, as a heads up, do realize that fileName.getBytes()
as you have there gets the bytes of the filename, not the file itself.
Second, reading inside the docs of FileReader:
The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
So, sounds like FileReader actually isn't the way to go. If we take the advice in the docs, then you should just change your code to have:
String fileName = getFileNameToReadFromUserInput();
FileInputStream is = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(is, getCorrectCharsetToApply());
BufferedReader buffReader = new BufferedReader(isr);
and not try to make a FileReader at all.
With Java 7+, you can create the Reader in one line:
BufferedReader buffReader = Files.newBufferedReader(Paths.get(fileName), getCorrectCharsetToApply());
Note that if you are using Google Guava, you can use Files.newReader
:
final BufferedReader reader =
Files.newReader(new File(filename), getCorrectCharsetToApply());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With