What is the shortest way to open file for reading with readLine() method and with setting of it's encoding?
Is the following line correct and shortest?
BufferedReader reader =
new BufferedReader(
new InputStreamReader(
new FileInputStream(myPath), myEncoding));
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. Methods: Using BufferedReader class.
Java supports several file-reading features. One such utility is reading a specific line in a file. We can do this by simply providing the desired line number; the stream will read the text at that location. The Files class can be used to read the n t h nth nth line of a file.
The readLine() method of Console class in Java is used to read a single line of text from the console. Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console. It returns null if the stream has ended.
Using the Scanner class Java Scanner class provides the nextLine() method to facilitates line by line of file's content. The nextLine() methods returns the same String as readLine() method. The Scanner class can also read a file form InputStream.
With Scanner, you can do: Scanner scan = new Scanner(new File(myPath), myEncoding)
and then scan.nextLine()
which returns a String
.
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