{"id":311,"date":"2018-03-07T20:49:54","date_gmt":"2018-03-07T20:49:54","guid":{"rendered":"http:\/\/loop.cs.mtu.edu\/?p=311"},"modified":"2023-11-06T17:29:55","modified_gmt":"2023-11-06T17:29:55","slug":"files-that-make-you-smile","status":"publish","type":"post","link":"https:\/\/loop.cs.mtu.edu\/index.php\/2018\/03\/07\/files-that-make-you-smile\/","title":{"rendered":"Files that Make You Smile"},"content":{"rendered":"<p><em><strong>Files<\/strong><\/em>.\u00a0 Those floppy, large things full of paper that used to be the bane of office workers are now electronic.\u00a0 No more lifting stacks of paper and having a couple of papers fall on the floor and get out of order!\u00a0 Instead we have to keep even more files in order inside folders, inside other folders on our computers.\u00a0 Not surprisingly, we have programs that can read and write files so we don&#8217;t have to do everything manually.<!--more--><\/p>\n<p>Overall, file reading is a simple process.\u00a0 Write a program that opens it up, scans through it, does something with the information, and closes it.\u00a0 File writing is about the same but slightly trickier because we have to read and store the original information, then print out all the information, old and new.\u00a0 Warning:\u00a0 if you are trying to open a file to both read and print at the same time it won&#8217;t work.\u00a0 Only one operation can check it out at any given time.\u00a0 Let&#8217;s get started:<\/p>\n<h2><strong>Read File &#8211; Read me a story &#8211; \u00a0please!<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">To read the contents of a file, we must know the filename, which we take in as a parameter. \u00a0We then create a new empty string to store the file contents. \u00a0<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public String readFile(String filename) {\r\n  String input = \"\";\r\n  try(Scanner scan = new Scanner(new File(filename))) {\r\n    while(scan.hasNext()) {\r\n      input += scan.nextLine() + \"\\n\";\r\n    }\r\n  } catch (FileNotFoundException e) {\r\n    e.printStackTrace();\r\n  }\r\n  return input;\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">Next comes the try-catch block. \u00a0Here, we use \u201ctry with resources\u201d, a mechanism where we declare a Scanner object and Java takes care of safely opening and closing it. \u00a0Be careful! \u00a0If you miss the \u201cnew File\u201d part of this, the Scanner will think it\u2019s supposed to be reading some unknown thing called <\/span><i><span style=\"font-weight: 400;\">filename<\/span><\/i><span style=\"font-weight: 400;\">. \u00a0Are these real files? \u00a0Yes, and no. \u00a0The File object that Java knows is a virtual representation of your file stored on the computer that lets it access it through a Scanner or PrintWriter. \u00a0Remember, you cannot just read a File object on its own!<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Once we have the Scanner opened up, we enter a while-loop that keeps on reading the file until the end, adding the next line to the input string each time it iterates. \u00a0We also add \u201c\\n\u201d the new line character to preserve the line breaks.<\/span><\/p>\n<h2><strong>Try it &#8211; but be ready to catch an exception<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">The catch section of the try-catch block says what to do if an exception is thrown. \u00a0A FileNotFoundException is caused by the absence of the specified file or a read\/write permission. \u00a0Often, this exception means your file is in the wrong place, or you misspelled it\u2019s name. \u00a0This exception will print a message like this to your console:<\/span><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-337 size-full\" src=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/GenericFileNotFound-e1524682950415.jpg\" alt=\"\" width=\"1540\" height=\"359\" srcset=\"https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/GenericFileNotFound-e1524682950415.jpg 1540w, https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/GenericFileNotFound-e1524682950415-300x70.jpg 300w, https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/GenericFileNotFound-e1524682950415-768x179.jpg 768w, https:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/GenericFileNotFound-e1524682950415-1024x239.jpg 1024w\" sizes=\"auto, (max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px\" \/><\/p>\n<p><span style=\"font-weight: 400;\">All this red ink says \u201cSorry, we can\u2019t find the file you told us to look for\u201d and gives you the <\/span><i><span style=\"font-weight: 400;\">stack trace<\/span><\/i><span style=\"font-weight: 400;\">, or series of commands, where things went wrong.\u00a0 One common error is having the file in the wrong folder, to trying to access a file in another folder without providing its absolute classpath.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400;\">An absolute class path is the full address of the file and might look like:\u00a0 C:\\Users\\Me\\Desktop\\MyJavaIdeas\\ProjectFiles\\TradCaesarCipherOrig.txt\u00a0 \u00a0 \u00a0 \u00a0 You can kind of imagine it as giving directions to a Martian so they can get to the White House:\u00a0 PlanetEarth\\NorthAmerica\\\u00a0<\/span><span style=\"font-weight: 400;\">UnitedStates\\Washington, D.C.\\1600PennsylvaniaAve.\u00a0 Basically, each program only knows its own file, so if it needs something from somewhere else, you have to give it the map to get there.\u00a0\u00a0<\/span><span style=\"font-weight: 400;\">Finally, we return the contents of the file as the string.<\/span><\/p>\n<h2><strong>Print File &#8211; Print out those words<\/strong><\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\">public void printFile(String fileOutput, String filename) {\r\n  try(PrintWriter print = new PrintWriter(new File(filename))) {\r\n    print.print(fileOutput);\r\n    System.out.println(fileOutput);\r\n  } catch (FileNotFoundException e) {\r\n    e.printStackTrace();\r\n  }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p><span style=\"font-weight: 400;\">This looks a lot like ReadFile, except it prints a file out using a PrintWriter. \u00a0The try-with-resources is about the same: \u00a0you declare and initialize the PrintWriter with a new File object, and Java does the opening, closing, and general cleanup. \u00a0The PrintWriter is a bit more forgiving than the Scanner, and will still figure out what to do if you omit the new File and just give it the filename. \u00a0Here, we print out to both the file and the console. \u00a0As with the Scanner, we use the catch part of the block to catch problems, typically if a write permission is denied.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Note: \u00a0when specifying the filenames for Scanner and PrintWriter, you must include the file extension. \u00a0A few common ones are .txt, , .in, .out, and .csv.\u00a0 Please note that Scanners and PrintWriters work with open-source format files, but you will get an error if you try to read or write a .docx file.<\/span><\/p>\n<p>That&#8217;s about it.\u00a0 Try out the code, making sure the file you&#8217;re trying to read exists and is where you tell the scanner to look.<\/p>\n<p>Download the Java file here:\u00a0\u00a0<a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/SimpleFileIO.java\"><span style=\"color: blue;\"><span style=\"color: #ff6600;\">SimpleFileIO.java<\/span><\/span><\/a>\u00a0, and view the text version in your browser here:\u00a0\u00a0<a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/SimpleFileIO.txt\"><span style=\"color: blue;\"><span style=\"color: #008000;\">SimpleFileIO.txt<\/span><\/span><\/a><\/p>\n<p>Two sample text files to copy between are\u00a0<a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/Stevenson.txt\"><span style=\"color: blue;\">Stevenson.txt<\/span><\/a>\u00a0and\u00a0<a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/03\/StevensonCopy.txt\"><span style=\"color: blue;\">StevensonCopy.txt<\/span><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Files.\u00a0 Those floppy, large things full of paper that used to be the bane of office workers are now electronic.\u00a0 No more lifting stacks of paper and having a couple of papers fall on the floor and get out of order!\u00a0 Instead we have to keep even more files in order inside folders, inside other &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/loop.cs.mtu.edu\/index.php\/2018\/03\/07\/files-that-make-you-smile\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Files that Make You Smile&#8221;<\/span><\/a><\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[31,1],"tags":[],"class_list":["post-311","post","type-post","status-publish","format-standard","hentry","category-java","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/311","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/comments?post=311"}],"version-history":[{"count":6,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/311\/revisions"}],"predecessor-version":[{"id":514,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/311\/revisions\/514"}],"wp:attachment":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/media?parent=311"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/categories?post=311"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/tags?post=311"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}