How to Read a Class File in Java Netbeans

The Java IO API provides two kinds of interfaces for reading files, streams and readers. The streams are used to read binary information and readers to read grapheme data. Since a text file is total of characters, you should exist using a Reader implementations to read information technology. In that location are several ways to read a plain text file in Java east.grand. you lot can use FileReader, BufferedReader or Scanner to read a text file. Every utility provides something special e.g. BufferedReader provides buffering of information for fast reading, and Scanner provides parsing power.

You tin as well use both BufferedReader and Scanner to read a text file line by line in Java. Then Coffee SE 8 introduces another Stream class java.util.stream.Stream which provides a lazy and more efficient manner to read a file.

The JDK 7 also introduces a couple of squeamish utility eastward.g. Files grade and try-with-resource construct which made reading a text file, even more, easier.

In this commodity, I am going to share a couple of examples of reading a text file in Java with their pros, cons, and of import points nigh each approach. This volition give you enough detail to choose the correct tool for the job depending on the size of file, the content of the file, and how you lot 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 Cord path to file or a java.io.File example to first reading. It too 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) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.shut();     }            catch            (IOException due east) {            // TODO Auto-generated catch block            e.printStackTrace();     }   }  Output Once upon a            fourth dimension, we wrote a programme to read            data            from a            text            file. The program failed to read a large file but then Coffee 8 come to rescue, which made reading file lazily using Streams.          

Yous can see that instead of reading ane grapheme at a fourth dimension, I am reading characters into an array. This is more efficient because read() will admission the file several times only read(char[]) volition access the file just one fourth dimension to read the same amount of data.

I am using an 8KB of the buffer, so in one call I am limited to read that much information simply. You tin can have a bigger or smaller buffer depending upon your heap memory and file size. Y'all should also notice that I am looping until read(char[]) returns -1 which signals the cease of the file.

Another interesting thing to note is to call to Cord.valueOf(buffer, 0, numberOfCharsRead), which is required because you might non have 8KB of data in the file or even with a bigger file, the concluding call may not be able to fill the char assortment and it could contain dirty information from the terminal read.

2. Reading a text file in Java using BufferedReader

The BufferedReader grade is a Decorator which provides buffering functionality to FileReader or any other Reader. This class buffer input from source eastward.g. files into memory for the efficient read. In the case of BufferedReader, the phone call to read() doesn't always goes to file if information technology tin find the information in the internal buffer of BufferedReader.

The default size of the internal buffer is 8KB which is good enough for well-nigh purpose, simply yous tin can also increase or decrease buffer size while creating BufferedReader object. The reading code is like to the previous example.

            public            static            void            readTextFileUsingBufferdReader(String            fileName) {            endeavour            {       FileReader textFileReader            =            new            FileReader(fileName);       BufferedReader bufReader            =            new            BufferedReader(textFileReader);        char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            bufReader.read(buffer);            // read volition be from            // memory            while            (numberOfCharsRead            !            =            -ane) {            Organization.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.shut();      }            grab            (IOException e) {            // TODO Auto-generated take hold of block            due east.printStackTrace();     }   }  Output [From File] Java provides several ways to read file

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

In social club to read the full-text file, you loop until read(char[]) method returns -i, which signals the end of the file. Run across Core Java Volume one - Fundamentals to learn more than virtually how BufferedReader class works in Java.

How to read a text file in Java

3. Reading a text file in Java using Scanner

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

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

The class uses regular expression blueprint to make up one's mind token, which could be catchy for newcomers. The two main method to read text data from Scanner is side by side() and nextLine(), onetime one read words separated past space while later one tin can be used to read a text file line by line in Java. In most cases, you would use the nextLine() method as shown below:

            public            static            void            readTextFileUsingScanner(Cord            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 cake            due east.printStackTrace();     }   } Output [From File] Coffee provides several ways to read the file.

You lot can use the hasNext() method to decide if there is any more token left to read in the file and loop until it returns false. Though you should recollect that next() or nextLine() may block until data is available fifty-fifty if hasNext() return true. This lawmaking is reading the content of "file.txt" line past line. See this tutorial to larn more about the Scanner class and file reading in Coffee.

4. Reading a text file using Stream in Java 8

The JDK 8 release has brought some cool new features due east.g. lambda expression and streams which make file reading fifty-fifty smoother in Java. Since streams are lazy, you can apply them to read-only lines you want from the file e.g. you can read all non-empty lines past filtering empty lines. The utilise of method reference too makes the file reading lawmaking much more unproblematic and curtailed, so much so that you can read a file in just i line as shown below:

Files.lines(Paths.become("newfile.txt")).forEach(Organization.out:            :println);  Output This is the            first            line of file  something is amend than nothing            this            is the            last            line of the file

Now, if you want to do some pre-processing, here is code to trim each line, filter empty lines to simply read not-empty ones, and remember, this is lazy because Files.lines() method return a stream of String and Streams are lazy in JDK eight (see Coffee 8 in Activity).

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

Nosotros'll utilise this lawmaking to read a file that contains a line that is total of whitespace and an empty line, the aforementioned one which nosotros have used in the previous example, but this time, the output will not contain v line but simply three lines because empty lines are already filtered, as shown beneath:

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

You can see only 3 out of five lines appeared because the other two got filtered. This is just the tip of the iceberg on what you can exercise with Java SE 8, See Java SE 8 for Really Impatient to learn more than nearly Coffee 8 features.

Reading text file in Java 8 example

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

Sometimes you read the full content of a text file equally String in Java. This is mostly the example with small text files equally for large files you will face up coffee.lang.OutOfMemoryError: coffee heap space fault. Prior to Java vii, this requires a lot of boiler code because yous need to use a BufferedReader to read a text file line past line and then add all those lines into a StringBuilder and finally return the String generated from that.

Now you don't demand to do all that, you can use the Files.readAllBytes() method to read all bytes of the file in one shot. One time done that you tin can convert that byte array into String. equally shown in the following example:

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

This was a rather small file and so it was pretty like shooting fish in a barrel. Though, while using readAllBytes() y'all should remember character encoding. If your file is not in platform'due south default character encoding then yous must specify the character doing explicitly both while reading and converting to String. Employ the overloaded version of readAllBytes() which accepts character encoding. You can also see how I read XML equally Cord in Java hither.

6. Reading the whole file in a List

Like to the final example, sometimes you demand all lines of the text file into an ArrayList or Vector or only on a List. Prior to Coffee 7, this job too involves boilerplate e.g. reading files line past line, adding them into a list, and finally returning the list to the caller, only after Java 7, it's very elementary now. Yous just demand to use the Files.readAllLines() method, which returns all lines of the text file into a List, as shown below:

            public            static            Listing<String> readFileInList(String            fileName) {            List<String> lines            =            Collections.emptyList();            try            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            catch            (IOException eastward) {            // TODO Car-generated catch block            e.printStackTrace();     }            render            lines; }

Similar to the final example, yous should specify graphic symbol encoding if it's different from than platform'south default encoding. Yous tin can use run across I have specified UTF-8 here. Again, employ this trick only if you know that file is minor and you have plenty retentivity to hold a List containing all lines of the text file, otherwise your Java plan will crash with OutOfMemoryError.

10 Examples to read text file in Java


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

This example is also very similar to the last two examples, this time, nosotros are reading the contents of the file into a Cord assortment. I have used a shortcut hither, first, I have read all the lines equally List and then converted the list to an array.

This results in simple and elegant code, but you lot can also read data into a grapheme array as shown in the first instance. Utilize the read(char[] information) method while reading data into a graphic symbol array.

Hither is an example of reading a text file into String assortment in Coffee:

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

This method leverage our existing method which reads the file into a Listing and the code here is only to convert a list to an array in Java.

8. 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 often need file information as line by line. Fortunately, both BufferedReader and Scanner provide convenient utility method to read line by line. If you are using BufferedReader then you lot can use readLine() and if you are using Scanner then you can use nextLine() to read file contents line by line. In our example, I take used BufferedReader as shown beneath:

            public            static            void            readFileLineByLine(Cord            fileName) {            try            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            String            line            =            br.readLine();            while            (line            !            =            nada) {            Organization.out.println(line);         line            =            br.readLine();       }     }            grab            (IOException e) {       e.printStackTrace();     }   }

Just call up that A line is considered to be terminated past any 1 of a line feed ('\northward'), a carriage return ('\r'), or a railroad vehicle return followed immediately by a line feed.

How to read a file line by line in Java

Java Programme to read a text file in Java

Hither is the complete Java program to read a plain text file in Java. You tin can run this program in Eclipse provided yous create the files used in this program e.g. "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 tin only create these files in the root of the project directory. The programme will throw FileNotFoundException or NoSuchFileExcpetion if information technology is non able to find the files.

            import            java.io.BufferedReader;            import            java.io.File;            import            java.io.FileNotFoundException;            import            coffee.io.FileReader;            import            java.io.IOException;            import            java.nio.charset.StandardCharsets;            import            coffee.nio.file.Files;            import            java.nio.file.Paths;            import            java.util.Collections;            import            java.util.List;            import            java.util.Scanner;            /*  * Java Program read a text file in multiple way.  * This program demonstrate how you can employ FileReader,  * BufferedReader, and Scanner to read text file,  * along with newer utility methods added in JDK 7  * and 8.   */            public            course            FileReadingDemo            {            public            static            void            main(String[] args) throws Exception {            // Example one - reading a text file using FileReader in Java            readTextFileUsingFileReader("sample.txt");            // Case 2 - reading a text file in Java using BufferedReader            readTextFileUsingBufferdReader("file.txt");            // Example three - reading a text file in Java using Scanner            readTextFileUsingScanner("file.txt");            // Example 4 - reading a text file using Stream in Java viii            Files.lines(Paths.become("newfile.txt")).forEach(Arrangement.out:            :println);            // Instance 5 - filtering empty lines from a file in Java 8            Files.lines(new            File("newfile.txt").toPath())     .map(south            -> s.trim())      .filter(s            ->            !s.isEmpty())      .forEach(System.out:            :println);            // Instance 6 - reading a text file equally String in Coffee            readFileAsString("file.txt");            // Example 7 - reading whole file in a Listing            List<String> lines            =            readFileInList("newfile.txt");            System.out.println("Full number of lines in file: "            +            lines.size());            // Case 8 - how to read a text file in java into an assortment            String[] arrayOfString            =            readFileIntoArray("newFile.txt");            for(Cord            line:            arrayOfString){            Organization.out.println(line);     }            // Instance ix - how to read a text file in java line by line            readFileLineByLine("newFile.txt");            // Example 10 - how to read a text file in java using eclipse            // all examples you tin run in Eclipse, in that location is naught special nearly it.                        }            public            static            void            readTextFileUsingFileReader(Cord            fileName) {            try            {       FileReader textFileReader            =            new            FileReader(fileName);       char[] buffer            =            new            char[8096];            int            numberOfCharsRead            =            textFileReader.read(buffer);            while            (numberOfCharsRead            !            =            -1) {            System.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }       textFileReader.close();     }            catch            (IOException e) {            // TODO Auto-generated catch block            e.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            // memory            while            (numberOfCharsRead            !            =            -i) {            Organization.out.println(String.valueOf(buffer, 0, numberOfCharsRead));         numberOfCharsRead            =            textFileReader.read(buffer);       }        bufReader.close();      }            catch            (IOException due east) {            // TODO Automobile-generated take hold of block            e.printStackTrace();     }   }            public            static            void            readTextFileUsingScanner(Cord            fileName) {            try            {       Scanner sc            =            new            Scanner(new            File(fileName));            while            (sc.hasNext()) {            String            str            =            sc.nextLine();            System.out.println(str);       }       sc.close();     }            catch            (IOException e) {            // TODO Auto-generated grab cake            e.printStackTrace();     }   }            public            static            Cord            readFileAsString(String            fileName) {            String            data            =            "";            try            {            data            =            new            Cord(Files.readAllBytes(Paths.get("file.txt")));     }            catch            (IOException eastward) {       e.printStackTrace();     }            render            data;   }            public            static            List<String> readFileInList(String            fileName) {            Listing<Cord> lines            =            Collections.emptyList();            attempt            {       lines            =            Files.readAllLines(Paths.get("file.txt"), StandardCharsets.UTF_8);     }            take hold of            (IOException e) {            // TODO Auto-generated take hold of block            east.printStackTrace();     }            render            lines;   }            public            static            String[] readFileIntoArray(String            fileName) {            Listing<Cord>            list            =            readFileInList(fileName);            return            list.toArray(new            Cord[list.size()]);    }            public            static            void            readFileLineByLine(Cord            fileName) {            effort            (BufferedReader br            =            new            BufferedReader(new            FileReader(fileName))) {            Cord            line            =            br.readLine();            while            (line            !            =            null) {            System.out.println(line);         line            =            br.readLine();       }     }            catch            (IOException e) {       east.printStackTrace();     }   } }

I have non printed the output here because nosotros have already gone through that and discuss in respective examples, only y'all need Java 8 to compile and run this program. If you lot are running on Java 7, then just remove the case 4 and five which uses Java 8 syntax and features and the program should run fine.

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

Other Java File tutorials for beginners

  • How to 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 Java? (guide)
  • How to read an XML file equally String in Java? (instance)
  • How to copy non-empty directories in Java? (example)
  • How to read/write from/to RandomAccessFile in Java? (tutorial)
  • How to suspend text to a File in Java? (solution)
  • How to read a ZIP file in Java? (tutorial)
  • How to read from a Memory Mapped file in Java? (example)

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

bautistaheremer.blogspot.com

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

0 Response to "How to Read a Class File in Java Netbeans"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel