In Java, you can use the InputStreamReader
class from the java.io
package to read a file as UTF-8 encoded characters. The InputStreamReader
class is a bridge from byte streams to character streams, and it reads bytes and decodes them into characters using a specified character set.
Here's an example of how to use the InputStreamReader
class to read a file as UTF-8 encoded characters in Java:
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) { String fileName = "path/to/file.txt"; try (BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(fileName), "UTF-8"))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
In this example, a BufferedReader
is created with an InputStreamReader
as input. The InputStreamReader
is created with a FileInputStream
and the character set "UTF-8". The BufferedReader
is then used to read lines from the file, and each line is printed to the console.
This code will read the file as UTF-8 encoded characters and print the contents to the console. You can use the InputStreamReader
class to read a file as UTF-8 encoded characters in Java.