How to read bytes from a UTF-8 text file in Java...

byte by byte.. Then create a String in memory in Java.

I have this file in my hard drive called: koray.txt. It is 3 bytes long and when I open the file with my text editor and see it as a UTF-8 encoded file, I will see:


And the code I have is:
final File file = new File("koray.txt");
final FileInputStream fileInputStream = new FileInputStream(file);
byte[] foo = new byte[3];
int read = fileInputStream.read();
foo[0] = (byte) read;
read = fileInputStream.read();
foo[1] = (byte) read;
read = fileInputStream.read();
foo[2] = (byte) read;
final String myString = new String(foo, "UTF-8");
System.out.println(myString);
Well, we tell Java to construct a String object, from the bytes stored in foo and treating the bytes as UTF-8.