Package Torello.Java

Class FileRW


  • public class FileRW
    extends java.lang.Object
    File Read / Write - Documentation.

    The purpose of this class is to simplify quite a few of the standard java.io.* file operations. The operations that Java provides are mostly "pretty useful" - however, if one is not overtly concerned with the optimization of disk reads or writes, what this package provides is many orders of code simplification. Many of the append, read and write operations instantiate a java.io.File and/or java.io.OutputStream, and open and close those Object's / classes in the same method/function body.

    FileRW.appendToFile(...) for instance, opens the File-Pointer, writes the String, and then closes it immediately. However, the 4 or 5 lines of code that each of these methods/functions eliminate make text-processing code and language-translation code a lot easier to read. With text-processing and language-translation, one might find oneself writing file data once a day, and never for very long. A few milliseconds is expended by opening and closing these file-pointers, but the code that I have written is world's easier to read.

    FileRW.writeObjectToFile(...) for instance, allows a user who is writing a Vector<String> (which for all intents-and-purposes is Java's way of saying "data-file" via "object-serialization"), to write the Vector to a file in a single line of code. This utilizes Java's object-serialization code, compression code, and file IO code in a single method, efficiently - saving a programmer potential for headache and bugs.

    Static (Functional) API: The methods in this class are all (100%) defined with the Java Key-Word / Key-Concept 'static'. Furthermore, there is no way to obtain an instance of this class, because there are no public (nor private) constructors. Java's Spring-Boot, MVC feature is *not* utilized because it flies directly in the face of the light-weight data-classes philosophy. This has many advantages over the rather ornate Component Annotations (@Component, @Service, @AutoWired, etc... 'Java Beans') syntax:

    • The methods here use the key-word 'static' which means (by implication) that there is no internal-state. Without any 'internal state' there is no need for constructors in the first place! (This is often the complaint by MVC Programmers).
    • A 'Static' (Functional-Programming) API expects to use fewer data-classes, and light-weight data-classes, making it easier to understand and to program.
    • The Vectorized HTML data-model allows more user-control over HTML parse, search, update & scrape. Also, memory management, memory leakage, and the Java Garbage Collector ought to be intelligible through the 'reuse' of the standard JDK class Vector for storing HTML Web-Page data.

    The power that object-oriented programming extends to a user is (mostly) limited to data-representation. Thinking of "Services" as "Objects" (Spring-MVC, 'Java Beans') is somewhat 'over-applying' the Object Oriented Programming Model. Like most classes in the Java-HTML JAR Library, this class backtracks to a more C-Styled Functional Programming Model (no Objects) - by re-using (quite profusely) the key-word static with all of its methods, and by sticking to Java's well-understood class Vector

    Static Field: The methods in this class do not create any internal state that is maintained - but there is a single private & static field defined. This field is instantiated only once during the Class Loader phase (and only if this class shall be used), and serves as a data 'lookup' field (like a static constant). View this class' source-code in the link provided below to see internally used data.

    This class has a single public, static, boolean field that is used to flag the file-reader logic regarding truncating EOF characters when reading text-files to String's



    • Field Detail

      • TRUNCATE_EOF_CHARS

        public static boolean TRUNCATE_EOF_CHARS
        This is used by method loadFileToString(String). By default this flag is set to TRUE, and when it is, any trailing EOF chars, ASCII-0 found in a file that is to be interpreted as a text-file, will be truncated from the String returned by that 'reader' method.
        Code:
        Exact Field Declaration Expression:
        1
        public static boolean TRUNCATE_EOF_CHARS = true;
        
    • Method Detail

      • writeFile

        public static void writeFile​(java.lang.CharSequence s,
                                     java.lang.String fName)
                              throws java.io.IOException
        Writes the entire contents of a single java.lang.String to a file on the file-system named 'fName'.

        NOTE: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java 'IOException' will occur.
        Parameters:
        s - A java.lang.String which is appended, in entirety, to the file ('fName')
        fName - The name of the file to which the contents of the java.lang.String are appended. If This file doesn't already exist, it is created here.
        Throws:
        java.io.IOException - If any I/O errors have occurred with the file-system / disk.
        Code:
        Exact Method Body:
        1
        2
        3
        4
        5
         File outF = new File(fName);
         outF.createNewFile();
         FileWriter fw = new FileWriter(outF);
         fw.write(s.toString());
         fw.close();
        
      • writeFile

        public static void writeFile​(java.lang.Iterable<java.lang.String> i,
                                     java.lang.String fName)
                              throws java.io.IOException
        Convenience Method. Invokes writeFile(Iterator, String)
        Code:
        Exact Method Body:
        1
         writeFile(i.iterator(), fName);
        
      • writeFile

        public static void writeFile​
                    (java.util.stream.Stream<java.lang.String> stringStream,
                     java.lang.String fName)
                throws java.io.IOException
        
        Convenience Method. Invokes writeFile(Iterator, String)
        Code:
        Exact Method Body:
        1
         writeFile(stringStream.iterator(), fName);
        
      • writeFile

        public static void writeFile​(java.util.Iterator<java.lang.String> i,
                                     java.lang.String fName)
                              throws java.io.IOException
        This takes an Iterator<String>, and a filename, and writes each java.lang.String in the Iterator to the file named by parameter 'fName'

        NOTE: A newline ('\n') is appended to the end of each java.lang.String before writing it to the file.

        ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java 'IOException' will occur.
        Parameters:
        i - This is any java Iterable<String> object. Each of these will be written, in succession, to the file named by parameter 'fName'
        fName - The name of the file to which the contents of the java.lang.String are appended. If This file doesn't already exist, it is created here.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
        1
        2
        3
        4
        5
         File outF = new File(fName);
         outF.createNewFile();
         FileWriter fw = new FileWriter(outF);
         while (i.hasNext()) fw.write(i.next() + "\n");
         fw.close();
        
      • writeFile_NO_NEWLINE

        public static void writeFile_NO_NEWLINE​
                    (java.lang.Iterable<java.lang.String> i,
                     java.lang.String fName)
                throws java.io.IOException
        
        Convenience Method. Invokes writeFile_NO_NEWLINE(Iterator, String)
        Code:
        Exact Method Body:
        1
         writeFile_NO_NEWLINE(i.iterator(), fName);
        
      • writeFile_NO_NEWLINE

        public static void writeFile_NO_NEWLINE​
                    (java.util.stream.Stream<java.lang.String> stringStream,
                     java.lang.String fName)
                throws java.io.IOException
        
        Convenience Method. Invokes writeFile_NO_NEWLINE(Iterator, String)
        Code:
        Exact Method Body:
        1
         writeFile_NO_NEWLINE(stringStream.iterator(), fName);
        
      • writeFile_NO_NEWLINE

        public static void writeFile_NO_NEWLINE​
                    (java.util.Iterator<java.lang.String> i,
                     java.lang.String fName)
                throws java.io.IOException
        
        This takes an Iterator of String, and a filename and writes each java.lang.String in the Iterator to the file named by parameter 'fName'

        NOTE: in this function a newline ('\n') character is not appended to the end of each java.lang.String of the input Iterator.

        ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java 'IOException' will occur.
        Parameters:
        i - This is any java 'Iterable' object that can iterate 'String'. Each of these will be written, in succession, to the file named by 'fName'
        fName - The name of the file to which the contents of the java.lang.String are appended. If This file doesn't already exist, it is created here.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
        1
        2
        3
        4
        5
         File outF = new File(fName);
         outF.createNewFile();
         FileWriter fw = new FileWriter(outF);
         while (i.hasNext()) fw.write(i.next());
         fw.close();
        
      • appendToFile

        public static void appendToFile​(java.lang.CharSequence s,
                                        java.lang.String fName)
                                 throws java.io.IOException
        Appends the entire input java.lang.String - actually a java.lang.CharSequence to the file on the file-system named 'fName'

        NOTE: Though the file does not need to exist already in order for this file to be written the directory hierarchy needs to exist, or a java 'IOException' will occur.
        Parameters:
        s - A java.lang.CharSequence (almost identical to 'String') which is appended, in entirety, to the file-name parameter 'fName'
        fName - The name of the file to which the contents of the java.lang.String are appended. If This file doesn't already exist, it is created here.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
        1
        2
        3
         File f = new File(fName);
         if (! f.exists()) f.createNewFile();
         Files.write(Paths.get(fName), s.toString().getBytes(), StandardOpenOption.APPEND);
        
      • loadFileToStringBuffer

        public static java.lang.StringBuffer loadFileToStringBuffer​
                    (java.lang.String fName)
                throws java.io.IOException
        
        Convenience Method. Invokes loadFileToString(String)
        Code:
        Exact Method Body:
        1
         return (new StringBuffer()).append(loadFileToString(fName));
        
      • loadFileToStringBuilder

        public static java.lang.StringBuilder loadFileToStringBuilder​
                    (java.lang.String fName)
                throws java.io.IOException
        
        Convenience Method. Invokes loadFileToString(String)
        Code:
        Exact Method Body:
        1
         return (new StringBuilder()).append(loadFileToString(fName));
        
      • loadFileToString

        public static java.lang.String loadFileToString​(java.lang.String fName)
                                                 throws java.io.IOException
        This will load the entire contents of a text-file on disk to a single java.lang.String

        TRUNCATES TRAILING ZEROES: Some of the ugliest code to see is that which finds 'EOF' characters liberally inserted into a simple text-file. When reading a file (which, regardless of whether it actually is a text-file), this method will remove any trailing ASCII-0 characters (literally, char c == 0) from the files that are read. Finding '.html' or '.java' files in which some editor (for whatever reason) has inserted EOF-like characters to the end of the text can make programming a headache.

        Suffice it to say, the String that is returned from this method will contain the last non-zero character (including CRLF, '\n' or '\r' character that was read from the file. Operating-systems do not need to have a trailing zero (legacy 'End-of-File' marker) at the end of a text-file in order to interpret that file. Java String's certainly have no use for them, and when worry about things like equality-tests inside Java loops, eliminating the EOF character altogether is actually best.

        FINALLY: This class has a static boolean flat can shunt this behavior, and all String's returned will include as many trailing zero characters at the end of the String returned by this method as the Java FileReader class finds. See TRUNCATE_EOF_CHARS.
        Parameters:
        fName - the file-name of a valid text-file in the file-system
        Returns:
        The entire contents of the file as a String.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
         FileReader  fr              = new FileReader(fName);
         int         len             = (int) new File(fName).length();
         char[]      cArr            = new char[len];
         int         offset          = 0;
         int         charsRead       = 0;
         int         charsRemaining  = len;
        
         try
         {
             while ((offset < len) && ((charsRead = fr.read(cArr, offset, charsRemaining)) != -1))
             {
                 offset          += charsRead;
                 charsRemaining  -= charsRead;
             }
         }
         finally
             { fr.close(); }
        
         len = cArr.length;
        
         if (TRUNCATE_EOF_CHARS) while ((len > 0) && (cArr[len-1] == 0)) len--;
        
         return (len != cArr.length) ? new String(cArr, 0, len) : new String(cArr);
        
      • loadFileToStringArray

        public static java.lang.String[] loadFileToStringArray​
                    (java.lang.String fName,
                     boolean includeNewLine)
                throws java.io.IOException
        
        Convenience Method. Invokes loadFileToStream(String, boolean)
        Code:
        Exact Method Body:
        1
         return loadFileToStream(fName, includeNewLine).toArray(String[]::new);
        
      • loadFileToStream

        public static java.util.stream.Stream<java.lang.String> loadFileToStream​
                    (java.lang.String fName,
                     boolean includeNewLine)
                throws java.io.IOException
        
        This will load a file to a java.lang.StringBuilder instance.
        Parameters:
        fName - A file-name of a valid text-file in the file-system.
        includeNewLine - if this is TRUE, a '\n' (newline/CRLF) is appended to the end of each java.lang.String read from this file. If not, the original newline characters which occur in the file, will be eliminated.

        MINOR NOTE: This method will make one (potentially minor) mistake. If the final character in the input-file is, itself, a new-line (if the file ends with a 'CRLF' / 'CR'), then this method should return a Stream<String> that is identical to the original file. However, if the final character in the file is not a new-line '\n', then the Stream<String> that is returned will have an extra new-line appended to the last String in the Stream, and the resultant Stream<String> will be longer than the original file by 1 character.
        Returns:
        The entire contents of the file as a series of java.lang.String contained by a java.util.stream.Stream<String>. Converting Java Stream's to other data container types is as follows:

        Conversion-Target Stream-Method Invocation
        String[] Stream.toArray(String[]::new);
        List<String> Stream.collect(Collectors.toList());
        Vector<String> Stream.collect(Collectors.toCollection(Vector::new));
        TreeSet<String> Stream.collect(Collectors.toCollection(TreeSet::new));
        Iterator<String> Stream.iterator();
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
         FileReader              fr  = new FileReader(fName);
         BufferedReader          br  = new BufferedReader(fr);
         Stream.Builder<String>  b   = Stream.builder();
         String                  s   = "";
        
         try
         {
             if (includeNewLine) while ((s = br.readLine()) != null) b.add(s + "\n");
             else                while ((s = br.readLine()) != null) b.add(s);
         }
         finally
             { fr.close(); }
        
         return b.build();
        
      • loadFileToVector

        public static java.util.Vector<java.lang.String> loadFileToVector​
                    (java.lang.String fName,
                     boolean includeNewLine)
                throws java.io.IOException
        
        Code:
        Exact Method Body:
        1
         return loadFileToCollection(new Vector<String>(), fName, includeNewLine);
        
      • loadFileToCollection

        public static <T extends java.util.Collection<java.lang.String>> T loadFileToCollection​
                    (T collectionChoice,
                     java.lang.String fName,
                     boolean includeNewLine)
                throws java.io.IOException
        
        This method loads the contents of a file to a java.util.Collection<String> object, where each java.lang.String in the output / returned Collection is a different "line of text" from the input-file. This is identical to using the method from public String[] java.lang.String 'split("\n")' - and then saving each of the String's from the String-array into an element of the returned Collection<String>

        This method uses Java's variable-type parameter syntax to allow the programmer to decide what type of Collection<String> to obtain from this method. The standard Java Collection's include: TreeSet, Vector, ArrayList, HashSet, among others. Provide a new Collection<String> by simply calling a constructor to one of these classes like: new Collection<String>().

        MINOR NOTE: This method will make one (potentially minor) mistake. If the final character in the input-file is, itself, a new-line (if the file ends with a 'CRLF' / 'CR'), then this method should return a Collection<String> that is identical to the original file. However, if the final character in the file is not a new-line '\n', then the Collection<String> that is returned will have an extra new-line appended to the last String in the Collection, and the resultant Collection<String> will be longer than the original file by 1 character.
        Parameters:
        collectionChoice - This must be an instance of a class that extends Java's base class Collection<String> - using 'String' as the generic-type parameter. It will be populated with the lines from a text-file using the Collection.add(String) method.
        fName - the file-name of a valid text-file on the file-system.
        includeNewLine - if this is TRUE, a '\n' (newline/CRLF) is appended to the end of each java.lang.String read from this file. If not, the original newline characters which occur in the file, will be eliminated.
        Returns:
        An identical reference to the reference passed to parameter 'collectionChoice'
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
         FileReader      fr  = new FileReader(fName);
         BufferedReader  br  = new BufferedReader(fr);
         String          s   = "";
        
         try
         {
             if (includeNewLine) while ((s = br.readLine()) != null) collectionChoice.add(s + "\n");
             else                while ((s = br.readLine()) != null) collectionChoice.add(s);
         }
         finally
             { fr.close(); }
        
         return collectionChoice;
        
      • writeObjectToFileNOCNFE

        public static boolean writeObjectToFileNOCNFE​(java.lang.Object o,
                                                      java.lang.String fName,
                                                      boolean ZIP)
                                               throws java.io.IOException
        Convenience Method. Invokes writeObjectToFile(Object, String, boolean), catches Exception.
        Code:
        Exact Method Body:
        1
        2
        3
        4
         try 
             { writeObjectToFile(o, fName, ZIP); return true; }
         catch (ClassNotFoundException cnfe)
             { return false; }
        
      • writeObjectToFile

        public static void writeObjectToFile​(java.lang.Object o,
                                             java.lang.String fName,
                                             boolean ZIP)
                                      throws java.io.IOException,
                                             java.lang.ClassNotFoundException
        Writes a java.lang.Object to a file for storage, and future reference.

        ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java IOException will occur.
        Parameters:
        o - An Object to be written to a file as a "Serializable" java.lang.Object
        fName - The name of the output file
        ZIP - a boolean that, when TRUE, will cause the object's data to be compressed before being written to the output file.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException - This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
         FileOutputStream        fos     = new FileOutputStream(fName);
        
         if (! ZIP)
         {
             ObjectOutputStream  oos     = new ObjectOutputStream(fos);
             oos.writeObject(o); oos.flush(); oos.close(); fos.close();
         }
         else
         {
             GZIPOutputStream    gzip    = new GZIPOutputStream(fos);
             ObjectOutputStream  oos     = new ObjectOutputStream(gzip);
             oos.writeObject(o); oos.flush(); gzip.finish(); oos.close(); fos.close();	
         }
        
      • writeAllObjectsToFile

        public static void writeAllObjectsToFile​(java.lang.Iterable<?> i,
                                                 java.lang.String fName,
                                                 boolean ZIP)
                                          throws java.io.IOException,
                                                 java.lang.ClassNotFoundException
        Code:
        Exact Method Body:
        1
         writeAllObjectsToFile(i.iterator(), fName, ZIP);
        
      • writeAllObjectsToFileNOCNFE

        public static boolean writeAllObjectsToFileNOCNFE​(java.lang.Iterable<?> i,
                                                          java.lang.String fName,
                                                          boolean ZIP)
                                                   throws java.io.IOException
        Convenience Method. Invokes writeAllObjectsToFile(Iterator, String, boolean), catches Exception.
        Code:
        Exact Method Body:
        1
        2
        3
        4
         try
             { writeAllObjectsToFile(i.iterator(), fName, ZIP); return true; }
         catch (ClassNotFoundException cnfe)
             { return false; }
        
      • writeAllObjectsToFileNOCNFE

        public static boolean writeAllObjectsToFileNOCNFE​(java.util.Iterator<?> i,
                                                          java.lang.String fName,
                                                          boolean ZIP)
                                                   throws java.io.IOException
        Convenience Method. Invokes writeAllObjectsToFile(Iterator, String, boolean), catches Exception.
        Code:
        Exact Method Body:
        1
        2
        3
        4
         try
             { writeAllObjectsToFile(i, fName, ZIP); return true; }
         catch (ClassNotFoundException cnfe)
             { return false; }
        
      • writeAllObjectsToFile

        public static void writeAllObjectsToFile​(java.util.Iterator<?> i,
                                                 java.lang.String fName,
                                                 boolean ZIP)
                                          throws java.io.IOException,
                                                 java.lang.ClassNotFoundException
        Writes a series of java.lang.Object to a file for storage, and future reference.

        ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java 'IOException' will occur.

        NOTE: When multiple java.lang.Object's need to be stored, it is sometimes advisable to save them to one of Java's many standard java.util.Collection classes, or possibly to a java.util.List class, first. Saving multiple Objects's to a java.util.Collection, and then writing that single Collection Object to disk can often make code look cleaner.

        Keep in mind that all of Java's 'java.util.*' generic data-structures implement the interface java.io.Serializable, so writing / serializing an entire Vector<Object> is extremely simple, as long as all of the Object's contained by the Vector also implement Serializable (or are 'de-facto' Serializable by the JVM).
        Parameters:
        i - A series, Collection, or List of Object's to be written to a file in Serializable format.
        fName - The name of the output file
        ZIP - a boolean that, when TRUE, will cause the Object's data to be compressed before being written to the output-file.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException - This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the CLASSPATH.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
         FileOutputStream        fos     = new FileOutputStream(fName);
        
         if (! ZIP)
         {
             ObjectOutputStream  oos     = new ObjectOutputStream(fos);
             while (i.hasNext()) oos.writeObject(i.next());
             oos.flush(); oos.close(); fos.close();
         } else
         {
             GZIPOutputStream    gzip    = new GZIPOutputStream(fos);
             ObjectOutputStream  oos     = new ObjectOutputStream(gzip);
             while (i.hasNext()) oos.writeObject(i.next());
             oos.flush(); gzip.finish(); oos.close(); fos.close();	
         }
        
      • readObjectFromFileNOCNFE

        public static java.lang.Object readObjectFromFileNOCNFE​
                    (java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException
        
        Convenience Method. Invokes readObjectFromFile(String, boolean). Catches Exception.
        Code:
        Exact Method Body:
        1
        2
        3
        4
         try 
             { return readObjectFromFile(fName, ZIP); }
         catch (ClassNotFoundException cnfe)
             { return null; }
        
      • readObjectFromFile

        public static java.lang.Object readObjectFromFile​
                    (java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException,
                       java.lang.ClassNotFoundException
        
        Reads an Object from a data-file which must contain a serialized java.lang.Object.

        Example:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
         // Create some Object for writing to the file-system, using Object Serialization
         int[] dataArr = some_data_method();
        
         // It is always easier to pass 'true' to the compression boolean parameter
         FileRW.writeObjectToFile(dataArr, "data/myDataFile.dat", true);
        
         ...
        
         // Later on, this file may be read back into the program, using this call:
         Object o = FileRW.readObjectFromFile("data/myDataFile.dat", true);
        
         // This check prevents compiler-time warnings.  The Annotation "SuppressWarnings" 
         // would also work.
         dataArr = (o instanceof int[]) ? (int[]) o : null;
         
        


        NOTE: When multiple java.lang.Object's need to be stored, it is sometimes advisable to save them to one of Java's many standard java.util.Collection classes, or possibly to a java.util.List class, first. Saving multiple Objects's to a java.util.Collection, and then writing that single Collection Object to disk can often make code look cleaner.

        Keep in mind that all of Java's 'java.util.*' generic data-structures implement the interface java.io.Serializable, so writing / serializing an entire Vector<Object> is extremely simple, as long as all of the Object's contained by the Vector also implement Serializable (or are 'de-facto' Serializable by the JVM).
        Parameters:
        fName - The name of a data-file that contains a serialized java.lang.Object
        ZIP - if this is TRUE, it is assumed that the data-file contains a zip-compressed Object
        Returns:
        The Object that was written to the data-file.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException - This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the CLASSPATH.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
         FileInputStream         fis     = new FileInputStream(fName);
         ObjectInputStream       ois     = ZIP   ? new ObjectInputStream(new GZIPInputStream(fis))
                                                 : new ObjectInputStream(fis);
         Object                  o;
        
         try 
             { o = ois.readObject(); }
         finally
             { fis.close(); }
        
         return o;
        
      • readObjectFromFileNOCNFE

        public static <T> T readObjectFromFileNOCNFE​(java.lang.String fName,
                                                     java.lang.Class<T> c,
                                                     boolean ZIP)
                                              throws java.io.IOException
        Convenience Method. Invokes readObjectFromFile(String, Class, boolean). Catches Exception.
        Code:
        Exact Method Body:
        1
        2
        3
        4
         try
             { return readObjectFromFile(fName, c, ZIP); }
         catch (ClassNotFoundException cnfe)
             { return null; }
        
      • readObjectFromFile

        public static <T> T readObjectFromFile​(java.lang.String fName,
                                               java.lang.Class<T> c,
                                               boolean ZIP)
                                        throws java.io.IOException,
                                               java.lang.ClassNotFoundException
        Reads an Object from a data-file which must contain a serialized java.lang.Object.

        NOTE: When multiple java.lang.Object's need to be stored, it is sometimes advisable to save them to one of Java's many standard java.util.Collection classes, or possibly to a java.util.List class, first. Saving multiple Objects's to a java.util.Collection, and then writing that single Collection Object to disk can often make code look cleaner.

        Keep in mind that all of Java's 'java.util.*' generic data-structures implement the interface java.io.Serializable, so writing / serializing an entire Vector<Object> is extremely simple, as long as all of the Object's contained by the Vector also implement Serializable (or are 'de-facto' Serializable by the JVM).
        Parameters:
        fName - The name of a data-file that contains a serialized java.lang.Object
        c - This is the type of the Object expecting to be read from disk. A value for this parameter can always be obtained by referencing the static field '.class' which is attached to every object in java.

        ALSO: The 'type parameter' (Class<T> c) is used to indicate the expected type of the java.lang.Object that is read, and ultimately returned. This method employs Java's variable-type method syntax. Variable-type parameter <T> may be any class at all (as long as were Serializable).

        Generally, the easiest way to obtain an instance of Class<T> is to just cite the field '.class' that every java.lang.Object contains. For instance, if a user was intending to read a TreeSet from disk, then specifying that an instance of Class<TreeSet> is desired would be as simple as passing TreeSet.class to this method's 'c' parameter.

        GENERIC-ERASURE: Generally because of the concept known as "Generic Erasure" - Variable-Type Parametrized Methods in Java do not function as well as they could. When reading a non-generic Object from a data-file, the read-operation implemented by this method should work just fine - as long as Java was able to 'serialize' the Object (which it is able to do most of the time regardless of whether the user has implemented the interface java.io.Serializable - by using 'de-facto', automated serialization).

        However, if writing, say, an instance of Vector<String>, the user needs to keep in mind that the stated return-type of this method, when passed the reference Vector.class, will be of a raw-type 'Vector', not of type Vector<String>. Therefore a 'cast' is in order, however, this 'cast' will generate a warning of unchecked cast - unless the @SuppressWarnings("unchecked") Annotation is carefully specified. Notice in the example how the Vector.class parameter, itself, is insufficient to return a a Vector<String>. Here, use a cast, and suppress the compiler warning messages:

        Example:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        // Generate a Data-Set, and save it to a String-Vector
        Vector<String> myData = some_data_operation();
        
        // Save this 'Object' (Vector) to disk, in a file named "StringVector.dat"
        // NOTE: Always passing "true" to the 'ZIP' parameter is usually easiest.
        // ALSO: We are writing *a single object* (a Vector), even though this Vector is a
        //       collection, it counts as just a single-object in this write.
        FileRW.writeObjectToFile(myData, "StringVector.dat", true);
        
        // To retrieve this Vector - as a Vector<String> reference - use the following
        // specifier and cast.  The "SuppressWarnings" is needed because this is a "generic"
        // type (Vector<E>)
        @SuppressWarnings("unchecked")
        myData = (Vector<String>) FileRW.readObjectFromFile("StringVector.dat", Vector.class, true);
        
        // The data-retrieval - AND COMPILER TYPE-CHECKING - should then work all right.
        // NOTE: This 'extra-cast' is *ONLY* important when serializing a generic-class that
        // uses the 'ClassName<E>' notation...
        // For serializing 'regular' classes:  String, Integer, etc... no such 'extra' cast
        // is needed - simply use:  String.class, Integer.class, etc...
        
        // *********************************************************************
        // IMPORTANT NOTE: The Same Rational Applies for the 'fromTextFile(...)'
        // object serializers:
        // *********************************************************************
        FileRW.writeObjectToTextFile(myData, "StringVector.txt");
        
        @SuppressWarnings("unchecked")
        myData = (Vector<String>) FileRW.readObjectFromTextFile("StringVector.txt", Vector.class);
        

        DATA-NOTE: If the file being read did not actually have a Vector which contained only instances of String, this could lead non-deterministic results (sometimes called "heap-pollution").
        ZIP - if this is TRUE, it is assumed that the data-file contains a zip-compressed Object
        Returns:
        The Object that was read from the data-file.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException - This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the CLASSPATH.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
         Object o = readObjectFromFile(fName, ZIP);
        
         if (o == null)          return null;
         if (c.isInstance(o))    return c.cast(o);
        
         throw new ClassNotFoundException(
             "Although an object was indeed read from the file you have named [" + fName + "], " +
             "that object was not an instance of [" + c.getName() + "], " + 
             "but rather of [" + o.getClass().getName() + "]"
         );
        
      • readAllObjectsToVector

        public static java.util.Vector<java.lang.Object> readAllObjectsToVector​
                    (java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException,
                       java.lang.ClassNotFoundException
        
        Code:
        Exact Method Body:
        1
         return readAllObjects(Object.class, new Vector<Object>(), fName, ZIP);
        
      • readAllObjectsToVector

        public static <T> java.util.Vector<T> readAllObjectsToVector​
                    (java.lang.Class<T> objType,
                     java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException,
                       java.lang.ClassNotFoundException
        
        Code:
        Exact Method Body:
        1
         return readAllObjects(objType, new Vector<T>(), fName, ZIP);
        
      • readAllObjects

        public static <T,​U extends java.util.Collection<T>> U readAllObjects​
                    (java.lang.Class<T> objType,
                     U collection,
                     java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException,
                       java.lang.ClassNotFoundException
        
        Reads all Object's found inside a data-file. This data-file should contain only java-serialized java.lang.Object's.
        Parameters:
        objType - This is the type / 'Class<C>' of the Object's that the user is expecting to read from disk. A value for this parameter can always be obtained by referencing the static field '.class' which is attached to every Object / Class in java. For instance, to read a data-file containing a series of java.lang.Integer instances, use Integer.class as the value to pass to this parameter. See below example:

        Example:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        // the java.util.TreeSet class is used to store a list of integers.
        TreeSet<Integer> myData = some_data_calculation();
        
        // Write this data-set to disk in a file-named "myDataFile.data"
        FileRW.writeAllObjectsToFile(myData, "etc/myDataFile.dat", true);
        
        // To read this file back from disk:
        // NOTE: The "SuppressWarnings" Annotation is NOT NEEDED HERE, because all
        //       available type information has been passed to the method.
        TreeSet<Integer> myData = FileRW.readAllObjects
            (Integer.class, new TreeSet<>(), "etc/myDataFile.dat", true);
        
        collection - This should be the desired Collection<E> that the programmer would like be populated with the instances of type 'objType' read from file 'fName'. Variable-Type parameter 'E' needs to be equal-to or an ancestor of 'objType'
        fName - The name of a data-file that contains serialized Object's
        ZIP - if this is TRUE, it is assumed that the data-file contains zip-compressed objects
        Returns:
        A reference to the Collection that was passed to this method.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
         Object                  o       = null;
         FileInputStream         fis     = new FileInputStream(fName);
         ObjectInputStream       ois     = ZIP   ? new ObjectInputStream(new GZIPInputStream(fis))
                                                 : new ObjectInputStream(fis);
        
         try
         {  
             while ((o = ois.readObject()) != null)
        
                 if (objType.isInstance(o))
                     collection.add(objType.cast(o));
        
                 else throw new ClassNotFoundException(
                     "At least one of the objects in the serialized object file [" + fName + "], " +
                     "was not an instance of [" + objType.getName() + "], " +
                     "but rather [" + o.getClass().getName() + "]"
                 );
         } 
         catch (EOFException eofe)
             { }
         finally
             { fis.close(); }
        
         return collection;
        
      • readAllObjectsToStream

        public static java.util.stream.Stream<java.lang.Object> readAllObjectsToStream​
                    (java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException,
                       java.lang.ClassNotFoundException
        
        Code:
        Exact Method Body:
        1
         return readAllObjectsToStream(Object.class, fName, ZIP);
        
      • readAllObjectsToStream

        public static <T> java.util.stream.Stream<T> readAllObjectsToStream​
                    (java.lang.Class<T> objType,
                     java.lang.String fName,
                     boolean ZIP)
                throws java.io.IOException,
                       java.lang.ClassNotFoundException
        
        Reads all objects found inside a data-file. This data-file should contain only java-serialized Object's.
        Parameters:
        fName - The name of a data-file that contains the serialized Object's
        objType - This is the type of the Object's expecting to be read from disk. A value for this parameter can always be obtained by referencing the static field '.class' which is attached to every Object in java. For instance, to read a data-file containing a series of Date instances, use Date.class as the value to pass to this parameter.
        ZIP - if this is TRUE, it is assumed that the data-file contains zip-compressed Object's
        Returns:
        A Stream<T> of all Object's found in the data-file. Converting Java Stream's to other data container types is as follows:

        Conversion-Target Stream-Method Invocation
        T[] Stream.toArray(T[]::new); /* Use Actual Class of T, generic array creation is not allowed in Java. */
        List<T> Stream.collect(Collectors.toList());
        Vector<T> Stream.collect(Collectors.toCollection(Vector::new));
        TreeSet<T> Stream.collect(Collectors.toCollection(TreeSet::new));
        Iterator<T> Stream.iterator();
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException - This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
         Stream.Builder<T>       b       = Stream.builder();
         Object                  o       = null;
         FileInputStream         fis     = new FileInputStream(fName);
         ObjectInputStream       ois     = ZIP   ? new ObjectInputStream(new GZIPInputStream(fis))
                                                 : new ObjectInputStream(fis);
        
         try
         {
             while ((o = ois.readObject()) != null)
        
                 if (objType.isInstance(o)) b.accept(objType.cast(o));
        
                 else throw new ClassNotFoundException(
                     "At least one of the objects in the serialized object file [" + fName + "], " +
                     "was not an instance of [" + objType.getName() + "], " +
                     "but rather [" + o.getClass().getName() + "]"
                 );
         }
         catch (EOFException eofe)
             { }
         finally
             { fis.close(); }
        
         return b.build();
        
      • writeObjectToTextFile

        public static void writeObjectToTextFile​(java.lang.Object o,
                                                 java.lang.String fileName)
                                          throws java.io.IOException
        Uses Java's Object serialization mechanism to serialize a java.lang.Object, and then uses the Base64 String-MIME Encoding system, also provided by java, to convert the Object into a text-safe java.lang.String that may be viewed, e-mailed, written to a web-page, etc.

        NOTE: When multiple java.lang.Object's need to be stored, it is sometimes advisable to save them to one of Java's many standard java.util.Collection classes, or possibly to a java.util.List class, first. Saving multiple Objects's to a java.util.Collection, and then writing that single Collection Object to disk can often make code look cleaner.

        Keep in mind that all of Java's 'java.util.*' generic data-structures implement the interface java.io.Serializable, so writing / serializing an entire Vector<Object> is extremely simple, as long as all of the Object's contained by the Vector also implement Serializable (or are 'de-facto' Serializable by the JVM).

        This loads the contents of an international website from Europe, and parses the output into a Vector<HTMLNode>. This output is printed to disk, and then it is saved as a B64 MIME-Encode String and also written to disk. Then this String is re-loaded and written out as HTML a second time to verify and ensure that no information was lost in the conversion of the Java 'POJO' into MIME-Encoded text.

        Example:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
            // Visit and parse a "Spanish Newspaper" (from Iberia, Spain).  Save to HTML Vector.
            URL                 url     = new URL("https://elpais.com/");
            Vector<HTMLNode>    html    = HTMLPage.getPageTokens(url, false);
        
            // Write the HTML out as a MIME-Encoded Java Serialized Object (of the Vector<HTMLNode>
            // The file itself will resemble 1990's e-mail MIME Messages.
            FileRW.writeObjectToTextFile(html, "myFile.txt");
        
            // Write the HTML out as a '.html' file
            FileRW.writeFile(Util.pageToString(html), "myFile1.html");
        
            // Reload the HTML Vector.  NOTE: Java's "Variable Type Parameters" will INVARIABLY produce warnings.
            // Here, the programmer must include a "@SuppressWarnings("unchecked")" in their method header,
            // or else he will receive an -Xlint:unchecked warnings.
            @SuppressWarnings("unchecked")
            html = (Vector<HTMLNode>>) FileRW.readObjectFromTextFile("myFile.txt", html.getClass());
        
            // Re-write the loaded HTML
            FileRW.writeFile(Util.pageToString(html), "myFile2.html");
        
            // NOTE: Using UNIX "diff -s myFile1.html myFile2.html" produces this:
            // Files myFile1.html and myFile2.html are identical
        
        Parameters:
        o - This may be any serializable java.lang.Object instance. It will be written to a text-file after first serializing the Object, and then next converting the serialized data-bits to MIME-safe encoded text.
        fileName - The fileName that will be used to save this Object as a text-file.
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
        1
         FileRW.writeFile(StringParse.objToB64MimeStr(o), fileName);
        
      • readObjectFromTextFile

        public static java.lang.Object readObjectFromTextFile​
                    (java.lang.String fileName)
                throws java.io.IOException
        
        This will read a java serialized, and MIME-Converted, MIME-Safe java.lang.String from a text file and return the Object that it represented

        NOTE: When multiple java.lang.Object's need to be stored, it is sometimes advisable to save them to one of Java's many standard java.util.Collection classes, or possibly to a java.util.List class, first. Saving multiple Objects's to a java.util.Collection, and then writing that single Collection Object to disk can often make code look cleaner.

        Keep in mind that all of Java's 'java.util.*' generic data-structures implement the interface java.io.Serializable, so writing / serializing an entire Vector<Object> is extremely simple, as long as all of the Object's contained by the Vector also implement Serializable (or are 'de-facto' Serializable by the JVM).
        Parameters:
        fileName - The name of the file containing the MIME-Encoded Serialized java.lang.Object.
        Returns:
        The Object that had been encoded into the text-file.
        Throws:
        java.io.IOException
        Code:
        Exact Method Body:
        1
         return StringParse.b64MimeStrToObj(loadFileToString(fileName));
        
      • readObjectFromTextFileNOCNFE

        public static <T> T readObjectFromTextFileNOCNFE​
                    (java.lang.String fileName,
                     java.lang.Class<T> c)
                throws java.io.IOException
        
        Convenience Method. Invokes readObjectFromTextFile(String, Class). Catches Exception.
        Code:
        Exact Method Body:
        1
        2
        3
        4
         try
             { return readObjectFromTextFile(fileName, c); }
         catch (ClassNotFoundException cnfe)
             { return null; }
        
      • readObjectFromTextFile

        public static <T> T readObjectFromTextFile​(java.lang.String fileName,
                                                   java.lang.Class<T> c)
                                            throws java.io.IOException,
                                                   java.lang.ClassNotFoundException
        This will read a java serialized, and MIME-Converted, MIME-Safe java.lang.String from a text file and return the Object that it represented

        NOTE: When multiple java.lang.Object's need to be stored, it is sometimes advisable to save them to one of Java's many standard java.util.Collection classes, or possibly to a java.util.List class, first. Saving multiple Objects's to a java.util.Collection, and then writing that single Collection Object to disk can often make code look cleaner.

        Keep in mind that all of Java's 'java.util.*' generic data-structures implement the interface java.io.Serializable, so writing / serializing an entire Vector<Object> is extremely simple, as long as all of the Object's contained by the Vector also implement Serializable (or are 'de-facto' Serializable by the JVM).

        This loads the contents of an international website from Europe, and parses the output into a Vector<HTMLNode>. This output is printed to disk, and then it is saved as a B64 MIME-Encode String and also written to disk. Then this String is re-loaded and written out as HTML a second time to verify and ensure that no information was lost in the conversion of the Java 'POJO' into MIME-Encoded text.

        Example:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
            // Visit and parse a "Spanish Newspaper" (from Iberia, Spain).  Save to HTML Vector.
            URL                 url     = new URL("https://elpais.com/");
            Vector<HTMLNode>    html    = HTMLPage.getPageTokens(url, false);
        
            // Write the HTML out as a MIME-Encoded Java Serialized Object (of the Vector<HTMLNode>
            // The file itself will resemble 1990's e-mail MIME Messages.
            FileRW.writeObjectToTextFile(html, "myFile.txt");
        
            // Write the HTML out as a '.html' file
            FileRW.writeFile(Util.pageToString(html), "myFile1.html");
        
            // Reload the HTML Vector.  NOTE: Java's "Variable Type Parameters" will INVARIABLY produce warnings.
            // Here, the programmer must include a "@SuppressWarnings("unchecked")" in their method header,
            // or else he will receive an -Xlint:unchecked warnings.
            @SuppressWarnings("unchecked")
            html = (Vector<HTMLNode>>) FileRW.readObjectFromTextFile("myFile.txt", html.getClass());
        
            // Re-write the loaded HTML
            FileRW.writeFile(Util.pageToString(html), "myFile2.html");
        
            // NOTE: Using UNIX "diff -s myFile1.html myFile2.html" produces this:
            // Files myFile1.html and myFile2.html are identical
        
        Parameters:
        fileName - The name of the file containing the MIME-Encoded Serialized java.lang.Object.
        c - This is the type of the Object expecting to be read from disk. A value for this parameter can always be obtained by referencing the static field '.class', which is attached to every Object in java.

        ALSO: The 'type parameter' (Class<T> c) is used to indicate the expected type of the java.lang.Object that is read, and ultimately returned. This method employs Java's variable-type method syntax. Variable-type parameter <T> may be any class at all (as long as were Serializable).

        Generally, the easiest way to obtain an instance of Class<T> is to just cite the field '.class' that every java.lang.Object contains. For instance, if a user was intending to read a TreeSet from disk, then specifying that an instance of Class<TreeSet> is desired would be as simple as passing TreeSet.class to this method's 'c' parameter.

        GENERIC-ERASURE: Generally because of the concept known as "Generic Erasure" - Variable-Type Parametrized Methods in Java do not function as well as they could. When reading a non-generic Object from a data-file, the read-operation implemented by this method should work just fine - as long as Java was able to 'serialize' the Object (which it is able to do most of the time regardless of whether the user has implemented the interface java.io.Serializable - by using 'de-facto', automated serialization).

        However, if writing, say, an instance of Vector<String>, the user needs to keep in mind that the stated return-type of this method, when passed the reference Vector.class, will be of a raw-type 'Vector', not of type Vector<String>. Therefore a 'cast' is in order, however, this 'cast' will generate a warning of unchecked cast - unless the @SuppressWarnings("unchecked") Annotation is carefully specified. Notice in the example how the Vector.class parameter, itself, is insufficient to return a a Vector<String>. Here, use a cast, and suppress the compiler warning messages:

        Example:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        // Generate a Data-Set, and save it to a String-Vector
        Vector<String> myData = some_data_operation();
        
        // Save this 'Object' (Vector) to disk, in a file named "StringVector.dat"
        // NOTE: Always passing "true" to the 'ZIP' parameter is usually easiest.
        // ALSO: We are writing *a single object* (a Vector), even though this Vector is a
        //       collection, it counts as just a single-object in this write.
        FileRW.writeObjectToFile(myData, "StringVector.dat", true);
        
        // To retrieve this Vector - as a Vector<String> reference - use the following
        // specifier and cast.  The "SuppressWarnings" is needed because this is a "generic"
        // type (Vector<E>)
        @SuppressWarnings("unchecked")
        myData = (Vector<String>) FileRW.readObjectFromFile("StringVector.dat", Vector.class, true);
        
        // The data-retrieval - AND COMPILER TYPE-CHECKING - should then work all right.
        // NOTE: This 'extra-cast' is *ONLY* important when serializing a generic-class that
        // uses the 'ClassName<E>' notation...
        // For serializing 'regular' classes:  String, Integer, etc... no such 'extra' cast
        // is needed - simply use:  String.class, Integer.class, etc...
        
        // *********************************************************************
        // IMPORTANT NOTE: The Same Rational Applies for the 'fromTextFile(...)'
        // object serializers:
        // *********************************************************************
        FileRW.writeObjectToTextFile(myData, "StringVector.txt");
        
        @SuppressWarnings("unchecked")
        myData = (Vector<String>) FileRW.readObjectFromTextFile("StringVector.txt", Vector.class);
        

        DATA-NOTE: If the file being read did not actually have a Vector which contained only instances of String, this could lead non-deterministic results (sometimes called "heap-pollution").
        Returns:
        The Object that had been encoded into the text-file.
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        java.lang.ClassNotFoundException - This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the CLASSPATH.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
         Object o = StringParse.b64MimeStrToObj(loadFileToString(fileName));
        
         if (o == null)          return null;
         if (c.isInstance(o))    return c.cast(o);
        
         throw new ClassNotFoundException(
             "Although an object was indeed read from the file you have named [" + fileName + "], " +
             "that object was not an instance of [" + c.getName() + "], " + 
             "but rather of [" + o.getClass().getName() + "]"
         );
        
      • getOIS

        public static java.io.ObjectInputStream getOIS​(java.lang.String fName,
                                                       boolean ZIP)
                                                throws java.io.IOException
        Creates a simple ObjectInputStream - usually if multiple Object's have been written to a single file. It was better practice to put Object's in a java.util.Vector, and write one java.util.Vector during serialization. This, eventually, can became inadequate when downloading large numbers of HTML results, where the need to write a large data-file (intermittently - by saving intermediate results) is needed.
        Parameters:
        fName - This is the file-name of the data-file where the serialized Object's have been stored.
        ZIP - If this is set to TRUE, the data will be de-compressed.
        Returns:
        A java ObjectInputStream
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
        1
        2
        3
         return ZIP
             ? new ObjectInputStream(new GZIPInputStream(new FileInputStream(new File(fName))))
             : new ObjectInputStream(new FileInputStream(new File(fName)));
        
      • getOOS

        public static java.io.ObjectOutputStream getOOS​(java.lang.String fName,
                                                        boolean ZIP)
                                                 throws java.io.IOException
        Creates a simple ObjectOutputStream - usually if multiple Object's need to be written to a single file. It was better practice to put Object's in a java.util.Vector, and write one java.util.Vector during serialization.
        Parameters:
        fName - This is the file-name of the data-file where the serialized Object's will be stored.
        ZIP - If this is set to TRUE, the data will be compressed.
        Returns:
        A java ObjectInputStream
        Throws:
        java.io.IOException - If an I/O error has occurred as a result of the file-system or disk operation.
        Code:
        Exact Method Body:
        1
        2
        3
         return ZIP
             ? new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(new File(fName))))
             : new ObjectOutputStream(new FileOutputStream(new File(fName)));
        
      • copyFile

        public static void copyFile​(java.lang.String inFileName,
                                    java.lang.String outFileOrDirName,
                                    boolean createDirsIfNotExist)
                             throws java.io.IOException
        This method will perform a byte-for-byte copy of a file from one location to another.
        Parameters:
        inFileName - The name of the input-file. It will be byte-for-byte copied to an output file-name.
        outFileOrDirName - The name of the output-file, or the name of the directory where the file shall be moved. If this file already exists and it is a file, not a directory, it will be over-written. If parameter 'outFileOrDirName' names a directory - due to having an ending File.separator, but does not appear to name directorie(s) that exist, this method will throw a FileNotFoundException. However, if parameter 'createDirsIfNotExist' is set to TRUE, even if parameter 'outFileOrDirName' names a directory (by virtue of the fact that it ends with the File.separator String) then this method will create the directory tree-structure using the standard Java's File.mkdirs() method.

        NOTE: The programmer may provide either a directory-name or a file-name to parameter 'outFileOrDirName'. If the programmer has provided a directory-name instead of a file-name, the moved file will have the same name as the original file ('inFileName') had, but it will be located in 'outFileOrDirName'.

        BEHAVIOR NOTE: The behavior of this copy operation is generally / mostly the same as the standard UNIX or MS-DOS commands 'cp' and 'copy' (respectively) - differing only in this method's ability to have directories created using File.mkdirs()
        createDirsIfNotExist - If the target output-file is situated in a directory-path that does not exist, this method will throw an exception. However, if this boolean parameter is set to TRUE and the aforementioned situation occurs where the complete-directory tree does not exist, then this method will first attempt to create the directories using java.io.File.mkdirs().
        Throws:
        java.lang.SecurityException - If boolean parameter 'createDirsIfNotExist' is TRUE and if the directory named by parameter 'outFileName' does not exist, and if attempting to create such a directory is not permitted by the Operating-System, then this exception shall throw.
        java.io.IOException - For any number of fail-causes in reading or writing input stream data. An explanation of all causes of such an operation is beyond the scope of this method-documentation entry.
        java.io.FileNotFoundException - If the 'inFileName' is not found, or 'outFileOrDirName' uses a directory path that doesn't exist on the file-system, and parameter 'createDirsIfNotExist' is set to FALSE.
        SameSourceAndTargetException - This exception will be thrown if the Java Virtual Machine ascertains that the source and target locations point to the same physical disk locations. The classes utilized for this operation are from package java.nio.file.*;
        java.nio.file.InvalidPathException - If the Java Virtual Machine is unable to instantiate an instance of java.nio.files.Path for either the 'inFileName' parameter or the 'outFileOrDirName', then this exception will be thrown.
        java.nio.file.NoSuchFileException - If, after instantiating an instance of Path for either the source or the target locations, the Java Virtual Machine is unable to build an instance of Path using the method Path.toRealPath(), then this exception will throw.
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
        29
        30
        31
        32
        33
        34
        35
        36
        37
        38
        39
         File f = new File(outFileOrDirName);
        
         if (createDirsIfNotExist) f.mkdirs();
        
         if (f.isDirectory())
         {
             if (! outFileOrDirName.endsWith(File.separator))
                 outFileOrDirName = outFileOrDirName + File.separator;
        
             outFileOrDirName = outFileOrDirName + StringParse.fromLastFileSeparatorPos(inFileName);
         }
        
         String inPath = Paths.get(inFileName).toRealPath().toString();
         // throws InvalidPathException
         // throws NoSuchFileException
        
         try
         {
             if (Paths.get(outFileOrDirName).toRealPath().toString().equals(inPath))
                 throw new SameSourceAndTargetException(
                     "The Source File Name and the Target Location provided to your copyFile " +
                     "request operation appear to point to the same physical-disk location:\n" +
                     inPath
                 );
         } catch (NoSuchFileException e) { }
         // NOTE: Mostly (but not always) the output file won't exist yet...  If it does not, 
         //       then we really don't need to worry about over-writing the origina file.  
         // REMEMBER: The only purpose of the above test is to make sure that the source and
         //           target are not the same (to avoid clobbering the original file)
        
         FileInputStream     fis     = new FileInputStream(inFileName);
         FileOutputStream    fos     = new FileOutputStream(outFileOrDirName);
         byte[]              b       = new byte[5000];
         int                 result  = 0;
        
         try
             { while ((result = fis.read(b)) != -1) fos.write(b, 0, result); }
         finally
             { fis.close();  fos.flush();  fos.close(); }
        
      • deleteFiles

        public static void deleteFiles​(java.lang.String... fileNames)
        Convenience Method. Invokes java.io.File.delete()
        Code:
        Exact Method Body:
        1
         for (String fileName : fileNames) (new File(fileName)).delete();
        
      • moveFile

        public static void moveFile​(java.lang.String inFileName,
                                    java.lang.String outFileName,
                                    boolean createDirsIfNotExist)
                             throws java.io.IOException
        Convenience Method. Invokes copyFile(String, String, boolean), and deletes.
        Code:
        Exact Method Body:
        1
        2
         copyFile(inFileName, outFileName, createDirsIfNotExist);
         (new File(inFileName)).delete();
        
      • delTree

        public static int delTree​(java.lang.String directoryName,
                                  boolean reCreateDirectoryOnExit,
                                  java.lang.Appendable log)
                           throws java.io.IOException
        This deletes an entire directory, including any sub-directories. It is like the UNIX switch -r for the command rm, or the old Microsoft DOS Command 'deltree' for deleting directories. It simply reuses the class FileTransfer

        NOTE: If this method is used on a UNIX or LINUX platform, then it ought to produce reults that are identical to an invocation of Shell.RM(directoryName, "-r"). However, if running on Windows, that method invocation would not function because it is a LINUX native API call. This method here is actually platform independent.
        Parameters:
        directoryName - This should be a valid directory on the file-system.

        WARNING: This command does indeed delete the entire directory-tree of the named directory!
        reCreateDirectoryOnExit - This parameter allows the user to create an an empty directory with the same name as the directory that was just deleted, after all of the directory's contents have been deleted. When this parameter is passed a value of TRUE, the equivalent of the UNIX command mkdir 'directoryName' will be executed prior to exiting this method.

        This can be a small convenience if the user desired that the directory be cleared, rather than deleted completely.
        log - This parameter may be null, and if it is, it will be ignored. This shall receive textual log output from the deletion process. This parameter expects an implementation of Java's interface java.lang.Appendable which allows for a wide range of options when logging intermediate messages.
        Class or Interface InstanceUse & Purpose
        'System.out'Sends text to the standard-out terminal
        Torello.Java.StorageWriterSends text to System.out, and saves it, internally.
        FileWriter, PrintWriter, StringWriterGeneral purpose java text-output classes
        FileOutputStream, PrintStreamMore general-purpose java text-output classes

        IMPORTANT: The interface Appendable requires that the check exception IOException must be caught when using its append(CharSequence) methods.
        Returns:
        This shall return a count on the total number of deleted files. Note that when directories are deleted (not files), their deletion shall not count towards the total returned in this integer.
        Throws:
        java.lang.IllegalArgumentException - Throws if the String provided to parameter directoryName does not name a valid directory on the File-System.
        java.io.IOException
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
         if (directoryName == null) throw new NullPointerException
             ("You have provided null to parameter 'directoryName', but this is not allowed here.");
        
         File f = new File(directoryName);
        
         if (! f.exists()) throw new IllegalArgumentException(
             "The directory name you have provided: [" + directoryName + "] was not found on the " +
             "File System.  Aborted."
         );
        
         if (! f.isDirectory()) throw new IllegalArgumentException(
             "The value you have provided to parameter 'directoryName' was: " + 
             "[" + directoryName + "], but unfortunately this is not the name of a directory on " +
             "the File System, but rather a file.  This is not allowed here."
         );
        
         // Uses class FileNode to build the directory into Java Memory.
         // It is possibly of interest to note, that if running this java code on a UNIX or
         // LINUX platform, this method should perform the exact same operation as an invocation
         // of Shell.RM(directoryName, "-r");
        
         FileNode fn = FileNode.createRoot(directoryName).loadTree();
        
         int ret = FileTransfer.deleteFilesRecursive(fn, null, null, log);
        
         if (reCreateDirectoryOnExit) f.mkdirs();
        
         return ret;
        
      • readIntsFromFile

        public static java.util.stream.IntStream readIntsFromFile​
                    (java.lang.String fileName,
                     boolean hasCommasInInts,
                     boolean isCSV,
                     int radix)
                throws java.io.FileNotFoundException,
                       java.io.IOException
        
        This may read a text-file containing integer data. If this data is a Comma Separated Value 'CSV' text-file, please pass TRUE to the parameter 'isCSV'. If this file contains integers that have commas between digits in groups of three (like '30,000') pleas pass TRUE to the parameter 'hasCommasInInts'.

        FILE FORMAT: The formatting of the file is not too particular. The 'flag' parameter 'isCSV' merely requires that the individual integers be separated by commas. There may be any number of such int's on a particular line, and any number of lines in the file. Blank lines are simply ignored. If 'isCSV' is set to FALSE, all numbers must be separated by some amount of white-space. Multiple numbers may still be placed on a single line (as long as there is white-space between them) even if 'isCSV' is FALSE.

        NUMBER FORMAT: The numbers in this text-file must be parse-able by Java's class java.lang.Integer using the method Integer.parseInt(String s, int radix)
        Parameters:
        fileName - This should contain the file-name which itself contains a list of integers. These integers may be separated by either a comma (',') or a space (' ').
        hasCommasInInts - It is allowed that the file named by 'fileName' contain integers which use the commonly found notation of having a comma between groups of three digits within an integer. For instance the number '98765', to a reader, is often represented as '98,765'. When this parameter is set to TRUE, this method shall simply remove any comma that is found juxtaposed between two digits before processing any text found in the file.
        isCSV - If the text file named by 'fileName' is a Comma Separated Value file, then please pass TRUE to this parameter. If FALSE is passed here, then it is mandatory that the individual numbers inside the text-file are separated by at least one white-space character.

        IMPORTANT: If it is decided to set both of the boolean parameters to TRUE - where the integers have commas, and the integers are separated by commas, it is up to the programmer to ensure that the individual numbers, themselves, are not only separated by a comma, but also separated by a space as well.
        radix - This is the 'radix', which is also usually called the number's 'base' that is to be used when parsing the numbers. Since Java's class java.lang.Integer is used to perform the parse, both the 'radix', and the data found in the text-file must conform to the Java method Integer.parseInt(String s, int radix).

        NOTE: This parameter may not be ignored. If the numbers in the text-file are to be interpreted as standard 'decimal' (Base 10) numbers, then the user should simply pass the constant '10' to this parameter.
        Returns:
        This method shall return a java.util.stream.IntStream consisting of the integers that were found within the text-file provided by 'fileName'.

        NOTE: An instance of IntStream is easily converted to an int[] array using the method IntStream.toArray().
        Throws:
        java.io.FileNotFoundException - If the file named by parameter 'fileName' is not found or not accessible in the file-system, then this exception will throw.
        java.io.IOException - This exception throws if there are any errors that occur while reading this file from the file-system.
        java.lang.NumberFormatException - If any of the numbers read from the text-file are not properly formatted, then this exception shall throw.
        See Also:
        StringParse.NUMBER_COMMMA_REGEX, StringParse.COMMA_REGEX, StringParse.WHITE_SPACE_REGEX
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
         FileReader              fr  = new FileReader(fileName);
         BufferedReader          br  = new BufferedReader(fr);
         IntStream.Builder       b   = IntStream.builder();
         String                  s   = "";
        
         while ((s = br.readLine()) != null)
         {
             // Skip blank lines.
             if ((s = s.trim()).length() == 0) continue;
        
             // This line simply finds String-Matches that match "Digit,Digit" and replaces
             // such matches with "DigitDigit".  After this replacement, they are parsed with ease.
             // NOTE: NUMBER_COMMMA_REGEX = Pattern.compile("\\d,\\d");
             if (hasCommasInInts)
                 s = StringParse.NUMBER_COMMMA_REGEX.matcher(s).replaceAll("$1$2").trim();
        
             String[] numbers = isCSV
                 ? StringParse.COMMA_REGEX.split(s)
                 : StringParse.WHITE_SPACE_REGEX.split(s);
         
             for (String number : numbers)
                 if ((number = number.trim()).length() > 0)
                     b.accept(Integer.parseInt(number, radix));
         }
        
         br.close();
         fr.close();
         return b.build();
        
      • readLongsFromFile

        public static java.util.stream.LongStream readLongsFromFile​
                    (java.lang.String fileName,
                     boolean hasCommasInLongs,
                     boolean isCSV,
                     int radix)
                throws java.io.FileNotFoundException,
                       java.io.IOException
        
        This may read a text-file containing integer data. If this data is a Comma Separated Value 'CSV' text-file, please pass TRUE to the parameter 'isCSV'. If this file contains integers that have commas between digits in groups of three (like '30,000') pleas pass TRUE to the parameter 'hasCommasInLongs'.

        FILE FORMAT: The formatting of the file is not too particular. The 'flag' parameter 'isCSV' merely requires that the individual long integers be separated by commas. There may be any number of such long's on a particular line, and any number of lines in the file. Blank lines are simply ignored. If 'isCSV' is set to FALSE, all numbers must be separated by some amount of white-space. Multiple numbers may still be placed on a single line (as long as there is white-space between them) even if 'isCSV' is FALSE.

        NUMBER FORMAT: The numbers in this text-file must be parse-able by Java's class java.lang.Long using the method Long.parseLong(String s, int radix)
        Parameters:
        fileName - This should contain the file-name which itself contains a list of 'long' integers. These long integers may be separated by either a comma (',') or a space (' ').
        hasCommasInLongs - It is allowed that the file named by 'fileName' contain long-integers which use the commonly found notation of having a comma between groups of three digits within a long integer. For instance the number '98765', to a reader, is often represented as '98,765'. When this parameter is set to TRUE, this method shall simply remove any comma that is found juxtaposed between two digits before processing any text found in the file.
        isCSV - If the text file named by 'fileName' is a Comma Separated Value file, then please pass TRUE to this parameter. If FALSE is passed here, then it is mandatory that the individual numbers inside the text-file are separated by at least one white-space character.

        IMPORTANT: If it is decided to set both of the boolean parameters to TRUE - where the long integers have commas, and the long integers are separated by commas, it is up to the programmer to ensure that the individual numbers, themselves, are not only separated by a comma, but also separated by a space as well.
        radix - This is the 'radix', which is also usually called the number's 'base' that is to be used when parsing the numbers. Since Java's class Long is used to perform the parse, both the 'radix', and the data found in the text-file must conform to the Java method Long.parseLong(String s, int radix).

        NOTE: This parameter may not be ignored. If the numbers in the text-file are to be interpreted as standard 'decimal' (Base 10) numbers, then the user should simply pass the constant '10' to this parameter.
        Returns:
        This method shall return a java.util.stream.LongStream consisting of the long-integers that were found within the text-file provided by 'fileName'.

        NOTE: An instance of LongStream is easily converted to a long[] array using the method LongStream.toArray().
        Throws:
        java.io.FileNotFoundException - If the file named by parameter 'fileName' is not found or not accessible in the file-system, then this exception will throw.
        java.io.IOException - This exception throws if there are any errors that occur while reading this file from the file-system.
        java.lang.NumberFormatException - If any of the numbers read from the text-file are not properly formatted, then this exception shall throw.
        See Also:
        StringParse.NUMBER_COMMMA_REGEX, StringParse.COMMA_REGEX, StringParse.WHITE_SPACE_REGEX
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
         FileReader              fr  = new FileReader(fileName);
         BufferedReader          br  = new BufferedReader(fr);
         LongStream.Builder      b   = LongStream.builder();
         String                  s   = "";
        
         while ((s = br.readLine()) != null)
         {
             // Skip blank lines.
             if ((s = s.trim()).length() == 0) continue;
        
             // This line simply finds String-Matches that match "Digit,Digit" and replaces
             // such matches with "DigitDigit".  After this replacement, they are parsed with ease.
             // NOTE: NUMBER_COMMMA_REGEX = Pattern.compile("\\d,\\d");
             if (hasCommasInLongs)
                 s = StringParse.NUMBER_COMMMA_REGEX.matcher(s).replaceAll("$1$2").trim();
        
             String[] numbers = isCSV
                 ? StringParse.COMMA_REGEX.split(s)
                 : StringParse.WHITE_SPACE_REGEX.split(s);
         
             for (String number : numbers)
                 if ((number = number.trim()).length() > 0)
                     b.accept(Long.parseLong(number, radix));
         }
        
         br.close();
         fr.close();
         return b.build();
        
      • readDoublesFromFile

        public static java.util.stream.DoubleStream readDoublesFromFile​
                    (java.lang.String fileName,
                     boolean hasCommasInDoubles,
                     boolean isCSV)
                throws java.io.FileNotFoundException,
                       java.io.IOException
        
        This may read a text-file containing floating-point data. If this data is a Comma Separated Value 'CSV' text-file, please pass TRUE to the parameter 'isCSV'. If this file contains double's that have commas between digits in groups of three (like '30,000,000,00') pleas pass TRUE to the parameter 'hasCommasInDoubles'.

        FILE FORMAT: The formatting of the file is not too particular. The 'flag' parameter 'isCSV' merely requires that the individual double values be separated by commas. There may be any number of such double's on a particular line, and any number of lines in the file. Blank lines are simply ignored. If 'isCSV' is set to FALSE, all numbers must be separated by some amount of white-space. Multiple numbers may still be placed on a single line (as long as there is white-space between them) even if 'isCSV' is FALSE.

        NUMBER FORMAT: The numbers in this text-file must be parseable by Java's class java.lang.Double using the method Double.parseDouble(String s)
        Parameters:
        fileName - This should contain the file-name which itself contains a list of 'double' values. These double's may be separated by either a comma (',') or a space (' ').
        hasCommasInDoubles - It is allowed that the file named by 'fileName' contain double-values which use the commonly found notation of having a comma between groups of three digits within a double value. For instance the number '98765.01', to a reader, can be represented as '98,765.01'. When this parameter is set to TRUE, this method shall simply remove any comma that is found juxtaposed between two digits before processing any text found in the file.
        isCSV - If the text file named by 'fileName' is a Comma Separated Value file, then please pass TRUE to this parameter. If FALSE is passed here, then it is mandatory that the individual numbers inside the text-file are separated by at least one white-space character.

        IMPORTANT: If it is decided to set both of the boolean parameters to TRUE - where the double values have commas, and the double values are separated by commas, it is up to the programmer to ensure that the individual numbers, themselves, are not only separated by a comma, but also separated by a space as well.
        Returns:
        This method shall return a java.util.stream.DoubleStream consisting of the double-values that were found within the text-file provided by 'fileName'.

        NOTE: An instance of DoubleStream is easily converted to a double[] array using the method DoubleStream.toArray().
        Throws:
        java.io.FileNotFoundException - If the file named by parameter 'fileName' is not found or not accessible in the file-system, then this exception will throw.
        java.io.IOException - This exception throws if there are any errors that occur while reading this file from the file-system.
        java.lang.NumberFormatException - If any of the numbers read from the text-file are not properly formatted, then this exception shall throw.
        See Also:
        StringParse.NUMBER_COMMMA_REGEX, StringParse.COMMA_REGEX, StringParse.WHITE_SPACE_REGEX
        Code:
        Exact Method Body:
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        25
        26
        27
        28
         FileReader              fr  = new FileReader(fileName);
         BufferedReader          br  = new BufferedReader(fr);
         DoubleStream.Builder    b   = DoubleStream.builder();
         String                  s   = "";
        
         while ((s = br.readLine()) != null)
         {
             // Skip blank lines.
             if ((s = s.trim()).length() == 0) continue;
        
             // This line simply finds String-Matches that match "Digit,Digit" and replaces
             // such matches with "DigitDigit".  After this replacement, they are parsed with ease.
             // NOTE: NUMBER_COMMMA_REGEX = Pattern.compile("\\d,\\d");
             if (hasCommasInDoubles)
                 s = StringParse.NUMBER_COMMMA_REGEX.matcher(s).replaceAll("$1$2").trim();
        
             String[] numbers = isCSV
                 ? StringParse.COMMA_REGEX.split(s)
                 : StringParse.WHITE_SPACE_REGEX.split(s);
         
             for (String number : numbers)
                 if ((number = number.trim()).length() > 0)
                     b.accept(Double.parseDouble(number));
         }
        
         br.close();
         fr.close();
         return b.build();