PUBLISHED ON: MARCH 26, 2021
Java DataInputStream readUTF() Method
In this tutorial, we will learn about the readUTF()
method of DataInputStream class in Java. This method is used to read a string that has been encoded using a modified UTF-8 (Uniform Text Format). The string of characters is decoded from the UTF and returned as String.
It is a non-static method, available in the java.io package.
Syntax
This is the declaration of this method. It does not accept any parameter and returns a Unicode string.
public final String readUTF()
Example 1: Read UTF Char in Java
This method is used to read the data that is encoded by the UTF-8 encoding, this method returns the data in the format of the string, in this example, it is returning the "Hello World".
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight
{
public static void main(String[] args) throws IOException
{
FileInputStream inputStream = new FileInputStream("E:\\studytonight\\file.txt");
DataInputStream dataInputStream = new DataInputStream(inputStream);
while(dataInputStream.available()>0)
{
String k = dataInputStream.readUTF();
System.out.print(k+" ");
}
}
}
Hello World
Example 2: Read UTF Char in Java
When there is no data to be read from the file then it will throw an exception that is also known as End Of File Exception because at this time the pointer points to the last position and will throw EOFException
.
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class StudyTonight
{
public static void main(String[] args) throws IOException
{
FileInputStream inputStream = new FileInputStream("E:\\studytonight\\file.txt");
DataInputStream dataInputStream = new DataInputStream(inputStream);
while(dataInputStream.available()>0)
{
String k = dataInputStream.readUTF();
System.out.print(k+" ");
}
}
}
Exception in thread "main" java.io.EOFException
at java.base/java.io.DataInputStream.readFully(DataInputStream.java:201)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:613)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:568)
at studytonight.StudyTonight.main(StudyTonight.java:16)
Conclusion
In this tutorial, we learned about the readUTF()
method of DataInputStream class in Java, which reads a string that has been encoded in UTF-8 format. The string of characters is decoded from the UTF and returned as String.