Title: Java Nio Read File Example - Java Code Geeks
Open Graph Title: Java Nio Read File Example - Java Code Geeks
Description: With this example we are going to demonstrate how to use the Non-blocking I/O API, or NIO.2 API (NIO API) for short, to read the contents of a file. The
Open Graph Description: With this example we are going to demonstrate how to use the Non-blocking I/O API, or NIO.2 API (NIO API) for short, to read the contents of a file. The
Mail addresses
support@javacodegeeks.com
Opengraph URL: https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/
Generator: WordPress 6.9.4
Domain: examples.javacodegeeks.com
{"@context":"https://schema.org","@graph":[{"@type":"Article","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#article","isPartOf":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/"},"author":{"name":"Aaron Witter","@id":"https://examples.javacodegeeks.com/#/schema/person/2b00d6b192e2567295f989fb2878618d"},"headline":"Java Nio Read File Example","datePublished":"2016-08-09T08:00:32+00:00","dateModified":"2023-11-09T13:25:14+00:00","mainEntityOfPage":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/"},"wordCount":597,"commentCount":0,"publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"image":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","keywords":["core java","java.io.BufferedReader","java.nio.file.Files","java.nio.file.Path","java.nio.file.Paths"],"articleSection":["Core Java"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#respond"]}]},{"@type":"WebPage","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/","url":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/","name":"Java Nio Read File Example - Java Code Geeks","isPartOf":{"@id":"https://examples.javacodegeeks.com/#website"},"primaryImageOfPage":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#primaryimage"},"image":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#primaryimage"},"thumbnailUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","datePublished":"2016-08-09T08:00:32+00:00","dateModified":"2023-11-09T13:25:14+00:00","description":"With this example we are going to demonstrate how to use the Non-blocking I/O API, or NIO.2 API (NIO API) for short, to read the contents of a file. The","breadcrumb":{"@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#primaryimage","url":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https://examples.javacodegeeks.com/java-development/core-java/java-nio-read-file-example/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://examples.javacodegeeks.com/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https://examples.javacodegeeks.com/category/java-development/"},{"@type":"ListItem","position":3,"name":"Core Java","item":"https://examples.javacodegeeks.com/category/java-development/core-java/"},{"@type":"ListItem","position":4,"name":"Java Nio Read File Example"}]},{"@type":"WebSite","@id":"https://examples.javacodegeeks.com/#website","url":"https://examples.javacodegeeks.com/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https://examples.javacodegeeks.com/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://examples.javacodegeeks.com/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https://examples.javacodegeeks.com/#organization","name":"Exelixis Media P.C.","url":"https://examples.javacodegeeks.com/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/logo/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2022/06/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https://examples.javacodegeeks.com/#/schema/logo/image/"},"sameAs":["https://www.facebook.com/javacodegeeks","https://x.com/javacodegeeks"]},{"@type":"Person","@id":"https://examples.javacodegeeks.com/#/schema/person/2b00d6b192e2567295f989fb2878618d","name":"Aaron Witter","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https://examples.javacodegeeks.com/#/schema/person/image/","url":"https://examples.javacodegeeks.com/wp-content/uploads/2016/07/Aaron-Witter-96x96.jpg","contentUrl":"https://examples.javacodegeeks.com/wp-content/uploads/2016/07/Aaron-Witter-96x96.jpg","caption":"Aaron Witter"},"description":"Aaron is a self-taught Certified Oracle Java programmer, with experience delivering high quality Java applications for a variety of UK Government Departments. Aaron has worked on projects ranging from the overhaul of the National Statistics website to delivering a portal for quality management in the National Health Service.","sameAs":["http://examples.javacodegeeks.com/"],"url":"https://examples.javacodegeeks.com/author/aaron-witter/"}]}
{"@context":"http:\/\/schema.org","@type":"BreadcrumbList","@id":"#Breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"item":{"name":"Home","@id":"https:\/\/examples.javacodegeeks.com\/"}},{"@type":"ListItem","position":2,"item":{"name":"Java Development","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"}},{"@type":"ListItem","position":3,"item":{"name":"Core Java","@id":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/core-java\/"}}]}
{"@context":"http:\/\/schema.org","@type":"Article","dateCreated":"2016-08-09T11:00:32+03:00","datePublished":"2016-08-09T11:00:32+03:00","dateModified":"2023-11-09T15:25:14+02:00","headline":"Java Nio Read File Example","name":"Java Nio Read File Example","keywords":"core java,java.io.BufferedReader,java.nio.file.Files,java.nio.file.Path,java.nio.file.Paths","url":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/java-nio-read-file-example\/","description":"With this example we are going to demonstrate how to use the Non-blocking I\/O API, or NIO.2\u00a0API (NIO API) for short, to read the contents of a file. The examples in this article are compiled and run i","copyrightYear":"2016","articleSection":"Core Java","articleBody":"With this example we are going to demonstrate how to use the Non-blocking I\/O API, or NIO.2\u00a0API (NIO API) for short, to read the contents of a file. The examples in this article are compiled and run in a Mac OS unix environment.\n\nPlease note that Java SE 8 is required to run the code in this article.\n\n1. Introduction to the NIO API\nThe NIO.2 API was introduced in Java 7 as a replacement for the java.io.File class. It provides a flexible, and intuitive API for use with files.\n2. Creating a NIO Path\nIn order to read a file from the file system we must first create a Path to the file.\u00a0\u00a0A Path object is a hierarchical representation of the path on a system to the file or directory. The java.nio.file.Path interface is the primary entry point for working with the NIO 2 API.\n\nThe easiest way to create a Path Object is to use the java.nio.files.Paths factory class. The class has a static get() method which can be used to obtain a reference to a file or directory. The method accepts either a string, or a sequence of strings(which it will join to form a path) as parameters. A java.nio.file.Path , like a File, may refer to either an absolute or relative path within the file system. \u00a0This is displayed in the following examples:\nPath p1 = Paths.get(\"cats\/fluffy.jpg\");\nPath p2 = Paths.get(\"\/home\/project\");\nPath p3 = Paths.get(\"\/animals\", \"dogs\", \"labradors\");\n\nIn the above:\n\n \tp1 creates a relative reference to a file in the current working directory.\n \tp2 creates a reference to an absolute directory in a Unix based system.\n \tp3 creates a reference to the absolute directory \/animals\/dogs\/labradors\n\n3. Reading files with the NIO API\nOnce we have a Path Object we are able to execute most of the operations that were previously possible with java.io.File.\n3.1 Using NIO API with newBufferedReader()\nThe\u00a0NIO.2 API has methods for reading files using java.io streams. \u00a0The Files.newBufferedReader(Path,Charset) reads the file found at the Path location, using the specified Charset for character encoding. Here's an example:\nPath path = Paths.get(\"src\/main\/resources\/shakespeare.txt\");\n try(BufferedReader reader = Files.newBufferedReader(path, Charset.forName(\"UTF-8\"))){\n\n \n String currentLine = null;\n while((currentLine = reader.readLine()) != null){\/\/while there is content on the current line\n System.out.println(currentLine); \/\/ print the current line\n }\n }catch(IOException ex){\n ex.printStackTrace(); \/\/handle an exception here\n }\n\n3.2 Using NIO API with readAllLines()\nAnother option is to use the Files.readAll() method, which will read the contents of a file and return them as an ordered list of strings. Here's an example of this method:\n Path path = Paths.get(\"src\/main\/resources\/shakespeare.txt\");\n try{\n\n List contents = Files.readAllLines(path);\n\n \/\/Read from the stream\n for(String content:contents){\/\/for each line of content in contents\n System.out.println(content);\/\/ print the line\n }\n\n }catch(IOException ex){\n ex.printStackTrace();\/\/handle exception here\n }\n\nNOTE: The readAllLines() method first commits the contents of the file to memory, as a result you may encounter an OutOfMemoryError if there is too much content.\n3.3 Using NIO API with streams\nWith Java 8 came the introduction of streams in place of the previously used methods of iteration. This makes it easy to lazily load lines from a file, using memory in a piecemeal fashion, and therefore preventing the OutOfMemoryError which was mentioned above. The example below shows how to make use of streams to achieve this:\n Path path = Paths.get(\"src\/main\/resources\/shakespeare.txt\");\n try {\n\n Files.lines(path).forEach(System.out::println);\/\/print each line\n\n } catch (IOException ex) {\n ex.printStackTrace();\/\/handle exception here\n }\n\nStream operations can be chained together into pipelines, which can make for some very powerful, declarative and concise code. For example, making use of the filter() operation on the above code in combination with the NIO API, allows us to to begin to analyse the contents of the file with ease.\n Path path = Paths.get(\"src\/main\/resources\/shakespeare.txt\");\n try {\n\n Files.lines(path)\n .filter(line -> line.startsWith(\"Love\")) \/\/ this line filters any line out which does not meet the condition\n .forEach(System.out::println);\/\/print each line\n\n } catch (IOException ex) {\n ex.printStackTrace();\/\/handle exception here\n }\n\nThe example above shows how simply we are able to begin looking at Shakespeare's lexical choices.\n4. Summary\nIn this article we've introduced you several ways to use the NIO API to read a file from your file system. Along the way we've touched upon the Path object and let you know the benefits of using one method over another.\n5. Download the Source Code\nBelow you can download the file read examples shown above:\nDownload\nYou can download the full source code of this example here: NIO API Read File Example","publisher":{"@id":"#Publisher","@type":"Organization","name":"Examples Java Code Geeks","logo":{"@type":"ImageObject","url":"\/wp-content\/uploads\/2013\/05\/JavaCodeGeeks-logo.png"},"sameAs":["https:\/\/feeds.feedburner.com\/examplesjavacodegeeks","https:\/\/www.facebook.com\/javacodegeeks","https:\/\/twitter.com\/javacodegeeks","https:\/\/www.linkedin.com\/groups\/3810709\/","https:\/\/www.youtube.com\/channel\/UCxoUc7Rar2q90Gu0nT2ffuQ","https:\/\/github.com\/javacodegeeks\/"]},"sourceOrganization":{"@id":"#Publisher"},"copyrightHolder":{"@id":"#Publisher"},"mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-development\/core-java\/java-nio-read-file-example\/","breadcrumb":{"@id":"#Breadcrumb"}},"author":{"@type":"Person","name":"Aaron Witter","url":"https:\/\/examples.javacodegeeks.com\/author\/aaron-witter\/"},"image":{"@type":"ImageObject","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":1200,"height":150}}
| og:locale | en_US |
| og:type | article |
| og:site_name | Examples Java Code Geeks |
| article:publisher | https://www.facebook.com/javacodegeeks |
| article:published_time | 2016-08-09T08:00:32+00:00 |
| article:modified_time | 2023-11-09T13:25:14+00:00 |
| og:image | https://examples.javacodegeeks.com/wp-content/uploads/2012/12/java-logo.jpg |
| og:image:width | 150 |
| og:image:height | 150 |
| og:image:type | image/jpeg |
| author | Aaron Witter |
| twitter:card | summary_large_image |
| twitter:creator | @javacodegeeks |
| twitter:label1 | Written by |
| twitter:data1 | Aaron Witter |
| twitter:label2 | Est. reading time |
| twitter:data2 | 3 minutes |
| None | IE=edge |
| msapplication-TileImage | https://examples.javacodegeeks.com/wp-content/uploads/2013/05/JavaCodeGeeks-favIcon.png |
Links:
Viewport: width=device-width, initial-scale=1.0
Robots: index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1