{"id":2487,"date":"2020-04-09T23:57:56","date_gmt":"2020-04-09T18:27:56","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=2487"},"modified":"2024-12-17T09:33:57","modified_gmt":"2024-12-17T14:33:57","slug":"reading-and-writing-text-file-in-java","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/reading-and-writing-text-file-in-java\/","title":{"rendered":"Reading and Writing text file in Java"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\"><strong>Introduction<\/strong> :<\/h2>\n\n\n\n<p>Reading and writing text file in Java is a fundamental skill for developers, enabling efficient data handling and file management. Java provides powerful classes like <code>FileReader<\/code>, <code>FileWriter<\/code>, <code>BufferedReader<\/code>, and <code>BufferedWriter<\/code> to seamlessly perform these operations. Whether you&#8217;re dealing with small text files or large data streams, understanding how to read and write text file in Java simplifies tasks like configuration management, logging, or data storage. This article will guide you through practical examples and best practices for working with text files in Java, ensuring you write clean, efficient, and reliable code.<\/p>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><b>Reading a text File in Java:<\/b><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"font-weight: 400;\">There are many ways to read a plain text file in <a href=\"https:\/\/www.java.com\/en\/\" data-type=\"link\" data-id=\"https:\/\/www.java.com\/en\/\" rel=\"nofollow noopener\" target=\"_blank\">Java program<\/a>.<\/span><\/li>\n\n\n\n<li><span style=\"font-weight: 400;\">We are using FileReader, BufferedReader, and Scanner to read a text file.\u00a0<\/span><\/li>\n\n\n\n<li><span style=\"font-weight: 400;\">This utility provides something special like:\u00a0<\/span>\n<ul class=\"wp-block-list\">\n<li><b>BufferedReader:<\/b><span style=\"font-weight: 400;\"> It provides buffering of data for fast reading.\u00a0<\/span><\/li>\n\n\n\n<li><b>Scanner:<\/b><span style=\"font-weight: 400;\"> It provides parsing ability.<\/span><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\"><b>A. BufferedReader:\u00a0<\/b><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"font-weight: 400;\">The BufferReader reads the text from a character-input stream.<\/span><\/li>\n\n\n\n<li><span style=\"font-weight: 400;\">It also did buffering for the reading of the characters, arrays, and the lines.<\/span><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe title=\"Working Behavior Of Java Language With Text File | How To Create Text File In Java || H2K Infosys\" width=\"800\" height=\"450\" src=\"https:\/\/www.youtube.com\/embed\/nc7doCxfNKQ?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p><span style=\"font-weight: 400;\">Let&#8217;s have an Example:<\/span><\/p>\n\n\n<p>[box type=&#8221;shadow&#8221; align=&#8221;&#8221; class=&#8221;&#8221; width=&#8221;&#8221;]BufferedReader in = new BufferedReader(Reader in, int size); [\/box]<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><b>Program:<\/b><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*; \npublic class ReadFile\n{ \n public static void main(String&#91;] arg)throws Exception \n { \n \n File fi = new File(\"C:\\\\Users\\\\read\\\\Desktop\\\\test.txt\"); \n \n BufferedReader br = new BufferedReader(new FileReader(fi)); \n \n String st; \n while ((st = br.readLine()) != null) \n System.out.println(st); \n } \n}<\/code><\/pre>\n\n\n\n<p><strong>B.&nbsp;FileReader Class:<\/strong> It is a class for reading character files.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*; \npublic class ReadingFile \n{ \n public static void main(String&#91;] arg) throws Exception \n { \n FileReader fileread= new FileReader(\"C:\\\\Users\\\\test\\\\Desktop\\\\test.txt\"); \n \n int i; \n while ((i=fileread.read()) != -1) \n System.out.print((char) i); \n } \n}\n<\/code><\/pre>\n\n\n\n<p><strong>How it Works:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>FileReader<\/code> opens the file for reading.<\/li>\n\n\n\n<li><code>BufferedReader<\/code> reads the file line by line using <code>readLine()<\/code>.<\/li>\n\n\n\n<li>The <code>try-with-resources<\/code> ensures that the file closes automatically after reading.<\/li>\n<\/ul>\n\n\n\n<p><b>C. Scanner Class:<\/b><span style=\"font-weight: 400;\">&nbsp;<\/span><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">A scanner which can parse the <a data-abc=\"true\" href=\"https:\/\/www.h2kinfosys.com\/blog\/java-variables-and-data-types\/\">primitive types<\/a> and also using strings through regular expressions.<\/span><\/span><\/li>\n\n\n\n<li><span style=\"font-weight: 400;\">A Scanner class can break its input into tokens, which by default matches whitespace.\u00a0<\/span><\/li>\n\n\n\n<li><span style=\"font-weight: 400;\">These resulting tokens may then be converted into values of different types using the various next methods.<\/span><\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Java Program to illustrate reading from Text File \n\/\/ using Scanner Class \nimport java.io.File; \nimport java.util.Scanner; \npublic class ReadFromFileUsingScanner \n{ \n public static void main(String&#91;] arg) throws Exception \n { \n \/\/ pass the path to the file as a parameter \n File file = new File(\"C:\\\\Users\\\\test\\\\Desktop\\\\test.txt\"); \n Scanner sc = new Scanner(file); \n \n while (sc.hasNextLine()) \n System.out.println(sc.nextLine()); \n } \n}<\/code><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><b>2. Introduction to Writing a text File in Java:<\/b><\/h2>\n\n\n\n<p>a. <strong>Java BufferedWriter Class<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Java BufferedWriter class is used to provide buffering for Writer instances.<\/li>\n\n\n\n<li>It makes the performance fast.<\/li>\n\n\n\n<li>It inherits the Writer class.<\/li>\n\n\n\n<li>The buffering characters are used for delivering the efficient writing of single arrays, characters, and strings.<\/li>\n\n\n\n<li>Creates a buffered character-output stream that uses a default-sized output buffer.<\/li>\n<\/ul>\n\n\n<p>[box type=&#8221;shadow&#8221; align=&#8221;&#8221; class=&#8221;&#8221; width=&#8221;&#8221;]public class BufferedWriter extends Writer [\/box]<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><b>Program:<\/b><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import java.io.*; \npublic class NewClass \n{ \n public static void main(String&#91;] args) \n { \n \/\/initializing FileWriter \n FileWriter filewrite; \n try\n { \nfilewrite = new FileWriter(\"ABC.txt\"); \n \n \/\/ Initialing BufferedWriter \n BufferedWriter bufferwrite = new BufferedWriter(filewrite); \n System.out.println(\"Buffered Writer start writing :)\"); \n \n \/\/ Use of write() method to write the value in 'ABC' file \n bufferwrite.write(69); \n bufferwrite.write(49); \n \n \/\/ Closing BufferWriter to end operation \n bufferwrite.close(); \n System.out.println(\"Written successfully\"); \n } \n catch (IOException excpt) \n { \n excpt.printStackTrace(); \n } \n \n } \n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">b) Java FileWriter Class<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>This class is used to write character-oriented data to a file.<\/li>\n\n\n\n<li>It is a character-oriented class which is used for file handling in java.<\/li>\n\n\n\n<li>Unlike the <a href=\"https:\/\/www.h2kinfosys.com\/blog\/what-is-restful-web-service\/\" data-type=\"post\" data-id=\"4183\">FileOutputStream class<\/a>, you don&#8217;t need to convert the string into a byte array because it provides a method to write string directly.<\/li>\n<\/ul>\n\n\n<p>[box type=&#8221;shadow&#8221; align=&#8221;&#8221; class=&#8221;&#8221; width=&#8221;&#8221;]public class FileWriter extends OutputStreamWriter [\/box]<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span style=\"font-weight: 400;\">&nbsp;<\/span><b>Program:&nbsp;&nbsp;&nbsp;<\/b><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code> import java.io.FileWriter; \n public class FileWriterExample { \n public static void main(String args&#91;]){ \n try{ \n FileWriter fw=new FileWriter(\"D:\\\\testout.txt\"); \n fw.write(\"Welcome\"); \n fw.close(); \n }\ncatch(Exception e)\n{\nSystem.out.println(e);\n} \n System.out.println(\"Success...\"); \n } \n }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Real-World Applications of File Handling<\/strong><\/h3>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Log Management<\/strong>: Applications generate logs to track errors and performance.<\/li>\n\n\n\n<li><strong>Data Storage<\/strong>: Store application settings and user preferences.<\/li>\n\n\n\n<li><strong>Report Generation<\/strong>: Export reports in text format.<\/li>\n\n\n\n<li><strong>Data Import\/Export<\/strong>: Transfer data between systems using files.<\/li>\n<\/ol>\n\n\n\n<p>File handling is widely used in backend development, making it a must-know for a <strong>Java Full Stack Developer<\/strong>.<\/p>\n\n\n\n<p><strong>Conclusion<\/strong><\/p>\n\n\n\n<p>Mastering file handling in Java is an essential skill for aspiring <strong><a href=\"https:\/\/www.h2kinfosys.com\/courses\/java-online-training-course-details\/\" data-type=\"link\" data-id=\"https:\/\/www.h2kinfosys.com\/courses\/java-online-training-course-details\/\">Java Full Stack Developers<\/a><\/strong>. Whether you\u2019re managing logs, storing user data, or working on backend systems, understanding how to read and write text file in java efficiently will set you apart in the industry.<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction : Reading and writing text file in Java is a fundamental skill for developers, enabling efficient data handling and file management. Java provides powerful classes like FileReader, FileWriter, BufferedReader, and BufferedWriter to seamlessly perform these operations. Whether you&#8217;re dealing with small text files or large data streams, understanding how to read and write text [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3785,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[496,58,493,495,494],"class_list":["post-2487","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials","tag-file","tag-java","tag-reading","tag-text","tag-writing"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/2487","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=2487"}],"version-history":[{"count":0,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/2487\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/3785"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=2487"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=2487"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=2487"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}