Java. IO. Encoding errors when reading a file
I have this method that reads the file:
private String fileContent = "";
void writeFile(String path) {
try (FileInputStream input = new FileInputStream(path)) {
int stream = input.read();
while (stream != -1) {
this.fileContent = String.format("%s%s", this.fileContent, ((char)stream));
stream = input.read();
}
} catch (IOException e) {
e.printStackTrace();
}
}
When I read the English alphabet from the file, everything is OK. But when I try to count the Cyrillic alphabet, I get hieroglyphs. Although in the file from which I read the UTF-8 encoding and in the development environment I have UTF-8 is. Can you tell me how to fix it?
1
1 answers
I decided like this. Maybe it will be useful for someone else. Directly from the file to the required encoding.
private String fileContent = "";
private void writeFile() {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream(this.path), "UTF-8"))) {
String sub;
while ((sub = br.readLine()) != null) {
this.fileContent = String.format("%s%s\n", this.fileContent, sub);
}
} catch (IOException e) {
e.printStackTrace();
}
}
4
Author: Pavel, 2016-12-04 08:15:47