How to Read Text File Hidden Characters

The Java IO API provides 2 kinds of interfaces for reading files, streams and readers. The streams are used to read binary data and readers to read character data. Since a text file is full of characters, you should be using a Reader implementations to read information technology. There are several ways to read a plain text file in Coffee east.grand. you can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.yard. BufferedReader provides buffering of information for fast reading, and Scanner provides parsing ability.

You can as well use both BufferedReader and Scanner to read a text file line by line in Java. Then Java SE eight introduces some other Stream form java.util.stream.Stream which provides a lazy and more efficient way to read a file.

The JDK vii also introduces a couple of nice utility e.thousand. Files course and endeavour-with-resources construct which made reading a text file, even more, easier.

In this article, I am going to share a couple of examples of reading a text file in Java with their pros, cons, and important points well-nigh each approach. This will give you enough particular to choose the correct tool for the job depending on the size of file, the content of the file, and how you want to read.

1. Reading a text file using FileReader

The FileReader is your general-purpose Reader implementation to read a file. It accepts a String path to file or a java.io.File instance to start reading. Information technology also provides a couple of overloaded read() methods to read a character or read characters into an array or into a CharBuffer object.

Here is an example of reading a text file using FileReader in Coffee:

            public            static            void            readTextFileUsingFileReader(String            fileName) {            endeavor            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            Organization.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.close();     }            catch            (IOException due east) {            // TODO Auto-generated catch block            e.printStackTrace();     }   }  Output Once upon a            fourth dimension, we wrote a program to read            data            from a            text            file. The programme failed to read a large file but then Coffee eight come to rescue, which made reading file lazily using Streams.          

Yous tin can come across that instead of reading one graphic symbol at a time, I am reading characters into an array. This is more efficient because read() volition admission the file several times but read(char[]) will access the file just once to read the aforementioned amount of data.

I am using an 8KB of the buffer, so in one phone call I am limited to read that much information merely. Yous can have a bigger or smaller buffer depending upon your heap retentiveness and file size. Y'all should also observe that I am looping until read(char[]) returns -i which signals the end of the file.

Another interesting matter to note is to call to Cord.valueOf(buffer, 0, numberOfCharsRead), which is required considering y'all might non have 8KB of data in the file or even with a bigger file, the last call may not be able to fill the char array and it could incorporate dingy information from the final read.

two. Reading a text file in Coffee using BufferedReader

The BufferedReader class is a Decorator which provides buffering functionality to FileReader or whatsoever other Reader. This course buffer input from source e.g. files into retentivity for the efficient read. In the case of BufferedReader, the call to read() doesn't always goes to file if it can find the data in the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is good enough for most purpose, but you tin can also increase or decrease buffer size while creating BufferedReader object. The reading code is similar to the previous example.

            public            static            void            readTextFileUsingBufferdReader(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       BufferedReader bufReader            =            new            BufferedReader(textFileReader);        char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            bufReader.read(buffer);            // read will be from            // memory            while            (numberOfCharsRead            !            =            -1) {            System.out.println(Cord.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            grab            (IOException e) {            // TODO Motorcar-generated grab cake            e.printStackTrace();     }   }  Output [From File] Java provides several ways to read file

In this example as well, I am reading the content of the file into an array. Instead of reading ane character at a time, this is more efficient. The only difference between the previous examples and this one is that the read() method of BufferedReader is faster than theread() method of FileReader because read tin happen from memory itself.

In order to read the full-text file, you loop until read(char[]) method returns -1, which signals the terminate of the file. Meet Core Java Volume 1 - Fundamentals to larn more than about how BufferedReader form works in Java.

How to read a text file in Java

3. Reading a text file in Coffee using Scanner

The third tool or class to read a text file in Java is the Scanner, which was added on JDK ane.5 release. The other two FileReader and BufferedReader are present from JDK one.0 and JDK ane.1 versions. The Scanner is a much more feature-rich and versatile class.

It does not only provide reading merely the parsing of data besides. Yous tin can not only read text data but yous can as well read the text as a number or float using nextInt() and nextFloat() methods.

The course uses regular expression pattern to determine token, which could be catchy for newcomers. The two main method to read text data from Scanner is side by side() and nextLine(), former one read words separated by space while subsequently one can be used to read a text file line by line in Java. In most cases, you would utilize the nextLine() method as shown below:

            public            static            void            readTextFileUsingScanner(String            fileName) {            try            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            String            str            =            sc.nextLine();            Organization.out.println(str);       }       sc.close();     }            catch            (IOException e) {            // TODO Auto-generated catch block            eastward.printStackTrace();     }   } Output [From File] Java provides several ways to read the file.

You can use the hasNext() method to determine if there is any more token left to read in the file and loop until it returns false. Though you lot should recall that next() or nextLine() may cake until data is available fifty-fifty if hasNext() return truthful. This code is reading the content of "file.txt" line past line. See this tutorial to learn more nigh the Scanner class and file reading in Java.

4. Reading a text file using Stream in Coffee 8

The JDK 8 release has brought some cool new features e.1000. lambda expression and streams which make file reading fifty-fifty smoother in Coffee. Since streams are lazy, you can use them to read-only lines you want from the file e.g. y'all tin read all not-empty lines by filtering empty lines. The utilise of method reference also makes the file reading code much more than simple and curtailed, so much so that yous can read a file in just ane line every bit shown below:

Files.lines(Paths.get("newfile.txt")).forEach(Arrangement.out:            :println);  Output This is the            starting time            line of file  something is ameliorate than nothing            this            is the            last            line of the file

Now, if y'all want to practice some pre-processing, hither is code to trim each line, filter empty lines to only read not-empty ones, and remember, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK viii (see Java viii in Action).

Files.lines(new            File("newfile.txt").toPath()) .map(due south            -> s.trim())  .filter(s            ->            !s.isEmpty())  .forEach(Organization.out:            :println);          

We'll apply this lawmaking to read a file that contains a line that is full of whitespace and an empty line, the aforementioned one which we accept used in the previous example, merely this time, the output will not comprise 5 line but just three lines because empty lines are already filtered, as shown below:

Output This is the            first            line of file something is better than nothing            this            is the            last            line of the file

You can see only three out of five lines appeared because the other 2 got filtered. This is only the tip of the iceberg on what you can practise with Java SE 8, See Java SE 8 for Really Impatient to learn more about Java 8 features.

Reading text file in Java 8 example

5. How to read a text file as String in Java

Sometimes y'all read the full content of a text file as Cord in Java. This is generally the case with minor text files every bit for large files you lot volition face java.lang.OutOfMemoryError: coffee heap infinite error. Prior to Java vii, this requires a lot of banality code because you demand to use a BufferedReader to read a text file line by line and and then add all those lines into a StringBuilder and finally render the String generated from that.

Now you don't need to do all that, you lot can utilize the Files.readAllBytes() method to read all bytes of the file in one shot. Once done that you tin can convert that byte assortment into String. every bit shown in the following example:

            public            static            String            readFileAsString(Cord            fileName) {            String            data            =            "";            try            {            data            =            new            String(Files.readAllBytes(Paths.get("file.txt")));     }            catch            (IOException due east) {       e.printStackTrace();     }            return            data;   } Output [From File] Java provides several ways to read file

This was a rather small file so it was pretty easy. Though, while using readAllBytes() you should remember character encoding. If your file is not in platform's default character encoding and so yous must specify the character doing explicitly both while reading and converting to String. Use the overloaded version of readAllBytes() which accepts character encoding. You can as well see how I read XML as String in Java hither.

half dozen. Reading the whole file in a List

Similar to the last example, sometimes you need all lines of the text file into an ArrayList or Vector or simply on a List. Prior to Java 7, this task also involves boilerplate e.thousand. reading files line past line, calculation them into a list, and finally returning the list to the caller, merely after Coffee 7, information technology'southward very unproblematic now. You only demand to use the Files.readAllLines() method, which returns all lines of the text file into a List, as shown below:

            public            static            List<String> readFileInList(Cord            fileName) {            Listing<String> lines            =            Collections.emptyList();            effort            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            take hold of            (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();     }            return            lines; }

Like to the terminal example, you should specify graphic symbol encoding if it'due south unlike from than platform's default encoding. You can apply see I have specified UTF-8 here. Again, use this trick only if you know that file is small and yous take enough memory to concur a List containing all lines of the text file, otherwise your Java program volition crash with OutOfMemoryError.

10 Examples to read text file in Java


7. How to read a text file in Java into an array

This example is likewise very similar to the concluding two examples, this time, we are reading the contents of the file into a String assortment. I have used a shortcut here, first, I have read all the lines every bit List so converted the list to an array.

This results in uncomplicated and elegant lawmaking, merely you can also read data into a graphic symbol array as shown in the first example. Use the read(char[] data) method while reading data into a grapheme assortment.

Hither is an example of reading a text file into String array in Java:

            public            static            String[] readFileIntoArray(String            fileName) {            List<String>            list            =            readFileInList(fileName);            return            listing.toArray(new            Cord[list.size()]); }

This method leverage our existing method which reads the file into a List and the code here is just to convert a list to an array in Coffee.

viii. How to read a file line by line in Java

This is i of the interesting examples of reading a text file in Coffee. You lot frequently demand file data as line by line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line by line. If you are using BufferedReader so you tin can use readLine() and if you are using Scanner then yous tin can utilise nextLine() to read file contents line by line. In our example, I accept used BufferedReader as shown below:

            public            static            void            readFileLineByLine(String            fileName) {            try            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            String            line            =            br.readLine();            while            (line            !            =            naught) {            Arrangement.out.println(line);         line            =            br.readLine();       }     }            catch            (IOException e) {       e.printStackTrace();     }   }

Just remember that A line is considered to be terminated by any ane of a line feed ('\due north'), a carriage return ('\r'), or a carriage return followed immediately past a line feed.

How to read a file line by line in Java

Java Program to read a text file in Java

Here is the consummate Java programme to read a plain text file in Java. You tin can run this programme in Eclipse provided you create the files used in this program e.one thousand. "sample.txt", "file.txt", and "newfile.txt". Since I am using a relative path, you must ensure that files are in the classpath. If you are running this program in Eclipse, you can only create these files in the root of the project directory. The program will throw FileNotFoundException or NoSuchFileExcpetion if it is not able to observe the files.

            import            java.io.BufferedReader;            import            java.io.File;            import            java.io.FileNotFoundException;            import            java.io.FileReader;            import            java.io.IOException;            import            java.nio.charset.StandardCharsets;            import            java.nio.file.Files;            import            java.nio.file.Paths;            import            java.util.Collections;            import            java.util.List;            import            coffee.util.Scanner;            /*  * Java Program read a text file in multiple way.  * This programme demonstrate how you tin use FileReader,  * BufferedReader, and Scanner to read text file,  * forth with newer utility methods added in JDK vii  * and eight.   */            public            form            FileReadingDemo            {            public            static            void            main(String[] args) throws Exception {            // Example ane - reading a text file using FileReader in Coffee            readTextFileUsingFileReader("sample.txt");            // Example 2 - reading a text file in Java using BufferedReader            readTextFileUsingBufferdReader("file.txt");            // Example 3 - reading a text file in Coffee using Scanner            readTextFileUsingScanner("file.txt");            // Instance 4 - reading a text file using Stream in Coffee viii            Files.lines(Paths.go("newfile.txt")).forEach(System.out:            :println);            // Example 5 - filtering empty lines from a file in Java viii            Files.lines(new            File("newfile.txt").toPath())     .map(s            -> south.trim())      .filter(south            ->            !s.isEmpty())      .forEach(System.out:            :println);            // Example 6 - reading a text file as Cord in Java            readFileAsString("file.txt");            // Example vii - reading whole file in a List            List<String> lines            =            readFileInList("newfile.txt");            Organization.out.println("Total number of lines in file: "            +            lines.size());            // Example viii - how to read a text file in java into an assortment            String[] arrayOfString            =            readFileIntoArray("newFile.txt");            for(String            line:            arrayOfString){            Organization.out.println(line);     }            // Instance nine - how to read a text file in coffee line past line            readFileLineByLine("newFile.txt");            // Example 10 - how to read a text file in coffee using eclipse            // all examples you can run in Eclipse, there is aught special about it.                        }            public            static            void            readTextFileUsingFileReader(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            Organisation.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.close();     }            catch            (IOException e) {            // TODO Auto-generated catch block            east.printStackTrace();     }   }            public            static            void            readTextFileUsingBufferdReader(String            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       BufferedReader bufReader            =            new            BufferedReader(textFileReader);        char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            bufReader.read(buffer);            // read will be from            // retentivity            while            (numberOfCharsRead            !            =            -1) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            catch            (IOException e) {            // TODO Auto-generated take hold of block            e.printStackTrace();     }   }            public            static            void            readTextFileUsingScanner(String            fileName) {            effort            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            String            str            =            sc.nextLine();            Organization.out.println(str);       }       sc.shut();     }            grab            (IOException eastward) {            // TODO Auto-generated take hold of cake            e.printStackTrace();     }   }            public            static            String            readFileAsString(String            fileName) {            String            data            =            "";            endeavour            {            data            =            new            String(Files.readAllBytes(Paths.get("file.txt")));     }            catch            (IOException eastward) {       eastward.printStackTrace();     }            return            data;   }            public            static            List<String> readFileInList(String            fileName) {            Listing<String> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            catch            (IOException east) {            // TODO Auto-generated catch block            e.printStackTrace();     }            return            lines;   }            public            static            String[] readFileIntoArray(String            fileName) {            List<String>            list            =            readFileInList(fileName);            render            listing.toArray(new            String[list.size()]);    }            public            static            void            readFileLineByLine(String            fileName) {            try            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            Cord            line            =            br.readLine();            while            (line            !            =            null) {            System.out.println(line);         line            =            br.readLine();       }     }            catch            (IOException due east) {       east.printStackTrace();     }   } }

I have not printed the output here because we have already gone through that and discuss in respective examples, merely you need Java 8 to compile and run this program. If y'all are running on Java 7, then just remove the instance four and 5 which uses Java viii syntax and features and the program should run fine.

That's all about how to read a text file in Java. We take looked at all major utilities and classes which you can use to read a file in Java likeFileReader, BufferedReader, and Scanner. We have likewise looked at utility methods added on Coffee NIO ii on JDK vii like. Files.readAllLines() and Files.readAllBytes() to read the file in List and String respectively.

Other Java File tutorials for beginners

  • How to bank check if a File is hidden in Java? (solution)
  • How to read an XML file in Java? (guide)
  • How to read an Excel file in Coffee? (guide)
  • How to read an XML file equally Cord in Coffee? (instance)
  • How to copy not-empty directories in Java? (example)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to append text to a File in Java? (solution)
  • How to read a Nil file in Java? (tutorial)
  • How to read from a Retentiveness Mapped file in Java? (case)

Finally, nosotros have also touched new fashion of file reading with Java 8 Stream, which provides lazy reading and the useful pre-processing option to filter unnecessary lines.

basssoperypear.blogspot.com

Source: https://javarevisited.blogspot.com/2016/07/10-examples-to-read-text-file-in-java.html

0 Response to "How to Read Text File Hidden Characters"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel