

{"id":14270,"date":"2018-04-21T06:07:20","date_gmt":"2018-04-21T06:07:20","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=14270"},"modified":"2021-12-04T10:16:23","modified_gmt":"2021-12-04T04:46:23","slug":"scala-file-io","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/scala-file-io\/","title":{"rendered":"Scala File i\/o: Open, Read and Write a File in Scala"},"content":{"rendered":"<p>In this tutorial Scala File io, we will learn how to Open, read and write files in Scala. I also recommend you to go through the<strong><a href=\"https:\/\/data-flair.training\/blogs\/scala-syntax\/\"> Scala Syntax <\/a><\/strong>and <strong><a href=\"https:\/\/data-flair.training\/blogs\/scala-functions\/\">Scala Functions <\/a><\/strong>Articles to clear your basics on Scala.<\/p>\n<p>So, let&#8217;s start Scala File io Tutorial.<\/p>\n<h3>Opening and Writing to a File in Scala<\/h3>\n<p>We don\u2019t have a class to write a file, in the Scala standard library, so we borrow java.io._ from Java. Or you could import java.io.File and java.io.PrintWriter.<\/p>\n<h4>a. The Import<\/h4>\n<pre class=\"EnlighterJSRAW\">C:\\Users\\lifei&gt;cd Desktop\r\nC:\\Users\\lifei\\Desktop&gt;scala<\/pre>\n<p>Welcome to Scala 2.12.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).<\/p>\n<p>Type in expressions for evaluation. Or try :help.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; import java.io._\r\nimport java.io._<\/pre>\n<h3><strong>Learn: <a href=\"https:\/\/data-flair.training\/blogs\/scala-data-types\/\">Scala Data Types with Examples<\/a><\/strong><\/h3>\n<h4>b. Creating a New File in Scala<\/h4>\n<p>To create a new file to write to, we create a new instance of PrintWriter, and pass a new File object to it.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val writer=new PrintWriter(new File(\"demo1.txt\"))\r\nwriter: java.io.PrintWriter = java.io.PrintWriter@31c7c281<\/pre>\n<h4>c. Writing to the File in Scala<\/h4>\n<p>Now, to write to the file, we call the method write() on the object we created.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; writer.write(\"This is a demo\")<\/pre>\n<h4>d. Finally<\/h4>\n<p>At this point, nothing is really visible in the file. To see these changes reflect in the file demo1.txt, we need to close it with Scala.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; writer.close()<\/pre>\n<p>Now, when we check the file demo1.txt again, we find:<\/p>\n<p>This is a demo<\/p>\n<p>Together, the code looks something like this:<\/p>\n<pre class=\"EnlighterJSRAW\">C:\\Users\\lifei&gt;cd Desktop\r\nC:\\Users\\lifei\\Desktop&gt;scala<\/pre>\n<p>Welcome to Scala 2.12.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_161).<\/p>\n<p>Type in expressions for evaluation. Or try :help.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; import java.io._\r\nimport java.io._\r\nscala&gt; val writer=new PrintWriter(new File(\"demo1.txt\"))\r\nwriter: java.io.PrintWriter = java.io.PrintWriter@31c7c281\r\nscala&gt; writer.write(\"This is a demo\")\r\nscala&gt; writer.close()<\/pre>\n<p><strong>Learn: <a href=\"https:\/\/data-flair.training\/blogs\/scala-variable\/\">Scala Variables with Examples<\/a><\/strong><\/p>\n<h3>Reading From a File in Scala<\/h3>\n<p>Now Scala does provide a class to read files. This is the class Source. We use its companion object to read files. For this demonstration, we\u2019re going to read what we put in the file demo1.txt. Let\u2019s begin.<\/p>\n<h4>a. The Import<\/h4>\n<p>The class we need to import here is scala.io.Source.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; import scala.io.Source\r\nimport scala.io.Source<\/pre>\n<h4>b. Reading From the File<\/h4>\n<p>To read the contents of this file, we call the fromFile() method of class Source- with the filename as argument. On this, we call the method mkString, like we\u2019ve seen in different collections so far.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; Source.fromFile(\"demo1.txt\").mkString\r\nres4: String = This is a demo<\/pre>\n<h4>c. Reading Between The Lines (Pun Intended)<\/h4>\n<p>To read individual lines instead of the whole file at once, we can use the getLines() method. For this, \u00a0we change the contents of our file to this:<\/p>\n<p>This is a demo<\/p>\n<p>This is line 2<\/p>\n<p>And this is line 3<\/p>\n<p>The code we use is:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; Source.fromFile(\"demo1.txt\").getLines.foreach{x=&gt;println(x)}<\/pre>\n<p>This is a demo<\/p>\n<p>This is line 2<\/p>\n<p>And this is line 3<\/p>\n<h3><strong>Learn:<a href=\"https:\/\/data-flair.training\/blogs\/scala-string-interpolation\/\"> Scala String Interpolation<\/a><\/strong><\/h3>\n<h4>d. Using an Iterator<\/h4>\n<p>We can also make use of an iterator to get one line at a time:<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Source.fromFile(\"demo1.txt\").getLines()\r\nit: Iterator[String] = non-empty iterator\r\nscala&gt; it.next()\r\nres9: String = This is a demo\r\nscala&gt; it.next()\r\nres10: String = This is line 2\r\nscala&gt; it.next()\r\nres11: String = And this is line 3\r\nscala&gt; it.next()<\/pre>\n<pre class=\"EnlighterJSRAW\">java.util.NoSuchElementException: next on empty iterator\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:38)\r\n at scala.collection.Iterator$$anon$2.next(Iterator.scala:36)\r\n at scala.io.BufferedSource$BufferedLineIterator.next(BufferedSource.scala:79)\r\n at scala.io.BufferedSource$BufferedLineIterator.next(BufferedSource.scala:64)\r\n ... 28 elided<\/pre>\n<h4>e. Extracting Individual Lines with take()<\/h4>\n<p>When we talked iterators, we saw the use of the method take(n) to return the first n values from the iterator. This is what we\u2019re going to use here.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Source.fromFile(\"demo1.txt\").getLines.take(2)\r\nit: Iterator[String] = non-empty iterator\r\nscala&gt; while(it.hasNext){print(it.next())}<\/pre>\n<p>This is a demoThis is line 2<\/p>\n<p>If we passed 1 to take(), it would only print \u201cThis is a demo\u201d.<\/p>\n<h4>f. Extracting Individual Lines with slice(start,until)<\/h4>\n<p>The method slice(start,until) returns an iterator over lines <i>start<\/i> to <i>until<\/i>-1.<\/p>\n<pre class=\"EnlighterJSRAW\">scala&gt; val it=Source.fromFile(\"demo1.txt\").getLines.slice(1,3)\r\nit: Iterator[String] = non-empty iterator\r\nscala&gt; while(it.hasNext){print(it.next())}<\/pre>\n<p>This is line 2And this is line 3<\/p>\n<p>So, this was all on Scala File io Tutorial. Hope you like our explanation.<\/p>\n<h3>Conclusion<\/h3>\n<p>So this is how you read and write a Scala file io. In this article, we saw use of methods write(), close(), fromFile(), getLines(), take(), and slice(). Furthermore, if you have any query, feel free to ask in the comment section.<\/p>\n<p><strong><a href=\"http:\/\/www.scala-lang.org\/old\/node\/3192\">For Reference<\/a><\/strong><span hidden class=\"__iawmlf-post-loop-links\" data-iawmlf-links=\"[{&quot;id&quot;:1964,&quot;href&quot;:&quot;http:\\\/\\\/www.scala-lang.org\\\/old\\\/node\\\/3192&quot;,&quot;archived_href&quot;:&quot;&quot;,&quot;redirect_href&quot;:&quot;https:\\\/\\\/www.scala-lang.org\\\/old\\\/node\\\/3192&quot;,&quot;checks&quot;:[],&quot;broken&quot;:false,&quot;last_checked&quot;:null,&quot;process&quot;:&quot;done&quot;}]\"><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial Scala File io, we will learn how to Open, read and write files in Scala. I also recommend you to go through the Scala Syntax and Scala Functions Articles to clear&#46;&#46;&#46;<\/p>\n","protected":false},"author":6,"featured_media":34739,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[61],"tags":[3115,9272,11377,12449],"class_list":["post-14270","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-scala","tag-creating-a-new-file","tag-opening-and-writing-to-a-file","tag-reading-from-the-file","tag-scala-file-io"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.0 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Scala File i\/o: Open, Read and Write a File in Scala - DataFlair<\/title>\n<meta name=\"description\" content=\"Scala File io:Learn to Open, read and write files in Scala. Also Learn to Import a new File, reading between the lines, using iterators.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/scala-file-io\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Scala File i\/o: Open, Read and Write a File in Scala - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Scala File io:Learn to Open, read and write files in Scala. Also Learn to Import a new File, reading between the lines, using iterators.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/scala-file-io\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-21T06:07:20+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-12-04T04:46:23+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-File-I-O-01-1.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Scala File i\/o: Open, Read and Write a File in Scala - DataFlair","description":"Scala File io:Learn to Open, read and write files in Scala. Also Learn to Import a new File, reading between the lines, using iterators.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/scala-file-io\/","og_locale":"en_US","og_type":"article","og_title":"Scala File i\/o: Open, Read and Write a File in Scala - DataFlair","og_description":"Scala File io:Learn to Open, read and write files in Scala. Also Learn to Import a new File, reading between the lines, using iterators.","og_url":"https:\/\/data-flair.training\/blogs\/scala-file-io\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2018-04-21T06:07:20+00:00","article_modified_time":"2021-12-04T04:46:23+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-File-I-O-01-1.jpg","type":"image\/jpeg"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/2c58ecb4f73a39f0ef993f1ddfcd7b89"},"headline":"Scala File i\/o: Open, Read and Write a File in Scala","datePublished":"2018-04-21T06:07:20+00:00","dateModified":"2021-12-04T04:46:23+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/"},"wordCount":582,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-File-I-O-01-1.jpg","keywords":["Creating a New File","Opening and Writing to a File","Reading From the File","Scala File io"],"articleSection":["Scala Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/scala-file-io\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/","url":"https:\/\/data-flair.training\/blogs\/scala-file-io\/","name":"Scala File i\/o: Open, Read and Write a File in Scala - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-File-I-O-01-1.jpg","datePublished":"2018-04-21T06:07:20+00:00","dateModified":"2021-12-04T04:46:23+00:00","description":"Scala File io:Learn to Open, read and write files in Scala. Also Learn to Import a new File, reading between the lines, using iterators.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/scala-file-io\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-File-I-O-01-1.jpg","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2018\/04\/Scala-File-I-O-01-1.jpg","width":1200,"height":628,"caption":"Scala File io: Open, Read and Write a File in Scala"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/scala-file-io\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"Scala Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/scala\/"},{"@type":"ListItem","position":3,"name":"Scala File i\/o: Open, Read and Write a File in Scala"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/2c58ecb4f73a39f0ef993f1ddfcd7b89","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/1ce4a0e3e542444fc73bbebf83e89e8b73e2d95ccb1fcee64da9945f078b97c5?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"The DataFlair Team provides industry-driven content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our expert educators focus on delivering value-packed, easy-to-follow resources for tech enthusiasts and professionals.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam2\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/14270","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=14270"}],"version-history":[{"count":6,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/14270\/revisions"}],"predecessor-version":[{"id":104778,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/14270\/revisions\/104778"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/34739"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=14270"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=14270"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=14270"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}