Package Torello.Java

Class FileRW


  • public class FileRW
    extends java.lang.Object
    Operating-System independent File Read & Write utilities that reduce many common Java File I/O Commands to a single method invocation, focusing heavily on Java's Serialization feature.

    The purpose of this class is to simplify & standardize several of the basic File & Disk Operations in Java. Though the number of lines of code that are saved by using this class is not a spectacular number, it can help simplify tasks where certain files are written frequently.

    The method FileRW.appendToFile for instance, opens the File-Pointer, writes the String-Parameter it is passed, and then closes the file immediately. The 4 or 5 lines of code that each of these methods/functions use, are eliminated. This has the potential make text-processing code and language-translation code a lot easier to both write & read.

    Object Serialization Methods:
    This class also makes anything involving writing or reading objects to & from disk tremendously easier. The method FileRW.writeObjectToFile for example, allows a user to write, say a 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 from potential hours of headache from trivial bugs.



    Stateless Class:
    This class neither contains any program-state, nor can it be instantiated. The @StaticFunctional Annotation may also be called 'The Spaghetti Report'. Static-Functional classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's @Stateless Annotation.

    • 1 Constructor(s), 1 declared private, zero-argument constructor
    • 41 Method(s), 41 declared static
    • 1 Field(s), 1 declared static, 0 declared final
    • Fields excused from final modifier (with explanation):
      Field 'TRUNCATE_EOF_CHARS' is not final. Reason: FLAG


    • Method Summary

       
      Read Text-Files
      Modifier and Type Method
      static <T extends Collection<String>>
      T
      loadFileToCollection​(T collectionChoice, String fName, boolean includeNewLine)
      static Stream<String> loadFileToStream​(String fName, boolean includeNewLine)
      static String loadFileToString​(String fName)
      static String[] loadFileToStringArray​(String fName, boolean includeNewLine)
      static Vector<String> loadFileToVector​(String fName, boolean includeNewLine)
       
      Write Text-Files
      Modifier and Type Method
      static void writeFile​(CharSequence s, String fName)
      static void writeFile​(Iterable<String> i, String fName)
      static void writeFile_NO_NEWLINE​(Iterable<String> i, String fName)
       
      Append Text to Text-Files
      Modifier and Type Method
      static void appendToFile​(CharSequence s, String fName)
      static void appendToFile​(Iterable<String> i, String fName, boolean addNewLines)
       
      Read a Single Serialized-Object from a File
      Modifier and Type Method
      static Object readObjectFromFile​(String fName, boolean ZIP)
      static <T> T readObjectFromFile​(String fName, Class<T> c, boolean ZIP)
      static Object readObjectFromFileNOCNFE​(String fName, boolean ZIP)
      static <T> T readObjectFromFileNOCNFE​(String fName, Class<T> c, boolean ZIP)
      static Object readObjectFromTextFile​(String fileName)
      static <T> T readObjectFromTextFile​(String fileName, Class<T> c)
      static <T> T readObjectFromTextFileNOCNFE​(String fileName, Class<T> c)
       
      Write a Single Serialized-Object to a File
      Modifier and Type Method
      static void writeObjectToFile​(Object o, String fName, boolean ZIP)
      static boolean writeObjectToFileNOCNFE​(Object o, String fName, boolean ZIP)
      static void writeObjectToTextFile​(Object o, String fileName)
       
      Read Multiple Serialized-Objects from a File
      Modifier and Type Method
      static <T,
           ​U extends Collection<T>>
      U
      readAllObjects​(Class<T> objType, U collection, String fName, boolean ZIP)
      static <T> Stream<T> readAllObjectsToStream​(Class<T> objType, String fName, boolean ZIP)
      static Stream<Object> readAllObjectsToStream​(String fName, boolean ZIP)
      static <T> Vector<T> readAllObjectsToVector​(Class<T> objType, String fName, boolean ZIP)
      static Vector<Object> readAllObjectsToVector​(String fName, boolean ZIP)
       
      Write Multiple Serialized-Objects to a File
      Modifier and Type Method
      static void writeAllObjectsToFile​(Iterable<?> i, String fName, boolean ZIP)
      static boolean writeAllObjectsToFileNOCNFE​(Iterable<?> i, String fName, boolean ZIP)
       
      Serialized Object I/O Stream
      Modifier and Type Method
      static ObjectInputStream getOIS​(String fName, boolean ZIP)
      static ObjectOutputStream getOOS​(String fName, boolean ZIP)
       
      Move, Copy & Delete
      Modifier and Type Method
      static void copyFile​(String inFileName, String outFileOrDirName, boolean createDirsIfNotExist)
      static void deleteFiles​(String... fileNames)
      static int delTree​(String directoryName, boolean reCreateDirectoryOnExit, Appendable log)
      static void moveFile​(String inFileName, String outFileName, boolean createDirsIfNotExist)
       
      Read Text-Numbers
      Modifier and Type Method
      static DoubleStream readDoublesFromFile​(String fileName, boolean hasCommasInDoubles, boolean isCSV)
      static IntStream readIntsFromFile​(String fileName, boolean hasCommasInInts, boolean isCSV, int radix)
      static LongStream readLongsFromFile​(String fileName, boolean hasCommasInLongs, boolean isCSV, int radix)
       
      Read & Write byte[]-Arrays to Binary-Files
      Modifier and Type Method
      static byte[] readBinary​(String fileName)
      static byte[] readBinary​(String fileName, int offset, int len)
      static Class<?> readClass​(String classFileName, String... possibleClassNames)
      static void writeBinary​(byte[] bArr, int offset, int len, String fileName)
      static void writeBinary​(byte[] bArr, String fileName)
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • 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.
    • 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'.

        Directory Requirements:
        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 be thrown.
        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:
         File outF = new File(fName);
        
         outF.createNewFile();
        
         // This writer is 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!
        
         try
             (FileWriter fw = new FileWriter(outF))
             { fw.write(s.toString()); }
        
      • writeFile

        🡅  🡇     🗕  🗗  🗖
        public static void writeFile​(java.lang.Iterable<java.lang.String> i,
                                     java.lang.String fName)
                              throws java.io.IOException
        This takes an Iterable<String>, and a filename, and writes each java.lang.String in the Iterator that it produces to the file specified by File-Name parameter 'fName'

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

        Directory Requirements:
        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 be thrown.
        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:
         Iterator<String> iter = i.iterator();
        
         File outF = new File(fName);
        
         outF.createNewFile();
        
         // This writer is 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!
        
         try
             (FileWriter fw = new FileWriter(outF))
             { while (iter.hasNext()) fw.write(iter.next() + "\n"); }
        
      • writeFile_NO_NEWLINE

        🡅  🡇     🗕  🗗  🗖
        public static void writeFile_NO_NEWLINE​
                    (java.lang.Iterable<java.lang.String> i,
                     java.lang.String fName)
                throws java.io.IOException
        
        This takes an Iterable of String, and a filename and writes each java.lang.String in the Iterator that it produces to the file specified by File-Name parameter 'fName'

        New-Line Characters:
        In this function a newline ('\n') character is not appended to the end of each java.lang.String of the input Iterator.

        Directory Requirements:
        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 be thrown.
        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:
         Iterator<String> iter = i.iterator();
        
         File outF = new File(fName);
        
         outF.createNewFile();
        
         // This Writer is 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!
        
         try
             (FileWriter fw = new FileWriter(outF))
             { while (iter.hasNext()) fw.write(iter.next()); }
        
      • 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'

        Directory Requirements:
        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:
         File f = new File(fName);
        
         if (! f.exists()) f.createNewFile();
        
         Files.write(Paths.get(fName), s.toString().getBytes(), StandardOpenOption.APPEND);
        
      • appendToFile

        🡅  🡇     🗕  🗗  🗖
        public static void appendToFile​(java.lang.Iterable<java.lang.String> i,
                                        java.lang.String fName,
                                        boolean addNewLines)
                                 throws java.io.IOException
        This takes an Iterable<String>, and a filename, and appends each java.lang.String in the Iterator that it produces to the file specified by File-Name parameter 'fName'

        Directory Requirements:
        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:
        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.
        addNewLines - When this parameter is passed TRUE, a New-Line character will be appended after each String that is written. When FALSE, only the String's produced by the Iterable, themselves, are appended to the file.
        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:
         File f = new File(fName);
        
         if (! f.exists()) f.createNewFile();
        
         // Uses the "Ternary Operator" / "Conditional Operator" Syntax, but it's a little hard to
         // read that.  There is a '?' and a ':' after the boolean 'addNewsLines'
        
         Iterable<String> passedIterable = addNewLines
        
             // If the user has requested to add newlines, wrap the passed Iterable inside of a new
             // Iterable that appends a new-line character to the output of the User's 'next()'
             // method (which is just returning the String's to be written to disk - less the newline)
        
             ?   new Iterable<>()
                 {
                     private final Iterator<String> iterInternal = i.iterator();
        
                     // Funny Note: All an "Iterable" is is an Object that returns an Iterator.  The
                     // interface "Iterable" only has one non-Default Method - iterator().  Re-Write
                     // that method to return a slightly altered Iterator<String>
        
                     public Iterator<String> iterator()
                     {
                         return new Iterator<String>()
                         {
                             public boolean  hasNext()   { return iterInternal.hasNext();        }
                             public String   next()      { return iterInternal.next() + '\n';    }
                         };
                     }
                 }
        
             // Otherwise, just assign the Users Iterable to the "passedIterable" Variable
             : i;
        
         // Now write the Passed Iterable of String, using java.nio.file.Files
         Files.write(Paths.get(fName), passedIterable, StandardOpenOption.APPEND);
        
      • 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

        Trailing Zeros:
        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 require that a file have a trailing zero to interpret them.

        Character '0' is a legacy / older-version of the EOF Marker. '.java'-Files certainly don't need them, and they can actually be a problem when a developer is checking for file's that have equal-String's in them.

        Static Boolean-Flag
        This class (class FileRW) has a static, boolean flag that is able to prevent / shunt this 'Trailing Zero Removing' behavior. When TRUNCATE_EOF_CHARS is set to FALSE, reading a file into a String using this method will return the String - including as many Trailing Zero-Characters as have been appended to the end of that file.
        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:
         // The reader is  'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!
        
         try
             (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;
        
             while ((offset < len) && ((charsRead = fr.read(cArr, offset, charsRemaining)) != -1))
             {
                 offset          += charsRead;
                 charsRemaining  -= charsRead;
             }
        
             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)
        Converts: Stream<String> into String[]
        Code:
        Exact Method Body:
         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 Stream 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:
         // These readers's are 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!
         //
         // ALSO: In try-with-resources blocks, if there is a problem/exception, these
         //       classes are all (automatically) closed/flushed, in reverse order.
        
         try (
             FileReader      fr  = new FileReader(fName);
             BufferedReader  br  = new BufferedReader(fr);
         )
         {
             Stream.Builder<String>  b = Stream.builder();
             String                  s = "";
        
             if (includeNewLine)
                 while ((s = br.readLine()) != null) b.add(s + "\n");
        
             else
                 while ((s = br.readLine()) != null) b.add(s);
        
             return b.build();
         }
        
      • 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 invoking:

        Java Line of Code:
         Collection<String> myTextFile = FileRW.loadFileToString("someFile.txt"0.split('\n')
        

        Variable-Type Parameter:
        This method uses Java's Variable-Type Parameter syntax to allow the programmer to decide what type of Collection<String> they would like returned from this method. Common examples would include Vector<String>, ArrayList<String>, HashSet<String> etc.

        Loading EOF:
        This method will make one small mistake. If the final character inside the input-file is, itself, a new-line, then this method will return a Java String-Collection which is is identical to the original file.

        However, if the final character in the file is not a new-line '\n' character, then the returned Collection will have an extra new-line appended immediately after the last String in the Collection. Furthermore, the resultant Collection<String> will be longer than the original file by 1 character.
        Type Parameters:
        T - This may be any class which extends java.util.Collection. It is specified as a "Type Parameter" because this collection is returned as a result of this function. Perhaps it is superfluous to return the same reference that is provided by the user as input to this method, but this certainly doesn't change the method signature or make it more complicated.
        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:
         // These readers's are 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!
         //
         // ALSO: In try-with-resources blocks, if there is a problem/exception, these
         //       classes are all (automatically) closed/flushed, in reverse order.
        
         try (
             FileReader      fr  = new FileReader(fName);
             BufferedReader  br  = new BufferedReader(fr);
         )
         {
             String s = "";
        
             if (includeNewLine)
                 while ((s = br.readLine()) != null) collectionChoice.add(s + "\n");
        
             else
                 while ((s = br.readLine()) != null) collectionChoice.add(s);
         }
        
         return collectionChoice;
        
      • 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.

        Directory Requirements:
        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 be thrown.
        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:
         // These stream's are 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException and ClassNotFoundException will still be thrown out of this
         //       method if they occur.  They are not caught!
         //
         // ALSO: In try-with-resources blocks, if there is a problem/exception, these
         //       classes are all (automatically) closed/flushed, in reverse order.
        
         if (ZIP)
        
             try (
                 FileOutputStream    fos     = new FileOutputStream(fName);
                 GZIPOutputStream    gzip    = new GZIPOutputStream(fos);
                 ObjectOutputStream  oos     = new ObjectOutputStream(gzip);
             )
                 { oos.writeObject(o); }
        
         else
        
             try (
                 FileOutputStream    fos     = new FileOutputStream(fName);
                 ObjectOutputStream  oos     = new ObjectOutputStream(fos);
             )
                 { oos.writeObject(o); }
        
      • writeAllObjectsToFile

        🡅  🡇     🗕  🗗  🗖
        public static void writeAllObjectsToFile​(java.lang.Iterable<?> 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.

        Directory Requirements:
        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 be thrown.

        Serializable Collections:
        When multiple java.lang.Object's need to be stored, it is very-often more advisable to first save those objects to one of Java's many java.util.Collection's or java.util.List's classes. Saving Serializable-Objects to a Collection or List, first, makes the code for writing of all of those objects, simultaneously, to disk look much more elegant and much cleaner / easier to read.

        Keep in mind that all of Java's 'java.util.*' Generic Data-Structure classes implement the Serializable interface, so writing / serializing an entire Vector (for instance) is extremely simple.

        The classes that you are trying to write to disk must also be serializable, although even if they haven't been declared serializable, explicitly, in your code, the JRE will still make an attempt to serialize them anyway using its best efforts.

        In summary, it is usually wiser to use the method writeObjectToFile(...) to write a single Java-Collection, than this method.
        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:
         Iterator<?> iter = i.iterator();
        
         // These stream's are 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException and ClassNotFoundException will still be thrown out of this
         //       method if they occur.  They are not caught!
         //
         // ALSO: In try-with-resources blocks, if there is a problem/exception, these
         //       classes are all (automatically) closed/flushed, in reverse order.
        
         if (ZIP)
        
             try (
                 FileOutputStream    fos     = new FileOutputStream(fName);
                 GZIPOutputStream    gzip    = new GZIPOutputStream(fos);
                 ObjectOutputStream  oos     = new ObjectOutputStream(gzip);
             )
                 { while (iter.hasNext()) oos.writeObject(iter.next()); }
        
         else
        
             try (
                 FileOutputStream    fos     = new FileOutputStream(fName);
                 ObjectOutputStream  oos     = new ObjectOutputStream(fos);
             )
                 { while (iter.hasNext()) oos.writeObject(iter.next()); }
        
      • 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:
         // 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;
        


        Serializable Collections:
        When multiple java.lang.Object's need to be stored, it is very-often more advisable to first save those objects to one of Java's many java.util.Collection's or java.util.List's classes. Saving Serializable-Objects to a Collection or List, first, makes the code for writing of all of those objects, simultaneously, to disk look much more elegant and much cleaner / easier to read.

        Keep in mind that all of Java's 'java.util.*' Generic Data-Structure classes implement the Serializable interface, so writing / serializing an entire Vector (for instance) is extremely simple.

        The classes that you are trying to write to disk must also be serializable, although even if they haven't been declared serializable, explicitly, in your code, the JRE will still make an attempt to serialize them anyway using its best efforts.

        In summary, it is usually wiser to use the method writeObjectToFile(...) to write a single Java-Collection, than this method.
        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:
         // These stream's are 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException and ClassNotFoundException will still be thrown out of this
         //       method if they occur.  They are not caught!
         //
         // ALSO: In try-with-resources blocks, if there is a problem/exception, these
         //       classes are all (automatically) closed/flushed, in reverse order.
        
         try (
             FileInputStream     fis = new FileInputStream(fName);
             ObjectInputStream   ois = ZIP
                                     ? new ObjectInputStream(new GZIPInputStream(fis))
                                     : new ObjectInputStream(fis);
         )
             { return ois.readObject(); }
        
      • 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.

        Serializable Collections:
        When multiple java.lang.Object's need to be stored, it is very-often more advisable to first save those objects to one of Java's many java.util.Collection's or java.util.List's classes. Saving Serializable-Objects to a Collection or List, first, makes the code for writing of all of those objects, simultaneously, to disk look much more elegant and much cleaner / easier to read.

        Keep in mind that all of Java's 'java.util.*' Generic Data-Structure classes implement the Serializable interface, so writing / serializing an entire Vector (for instance) is extremely simple.

        The classes that you are trying to write to disk must also be serializable, although even if they haven't been declared serializable, explicitly, in your code, the JRE will still make an attempt to serialize them anyway using its best efforts.

        In summary, it is usually wiser to use the method writeObjectToFile(...) to write a single Java-Collection, than this method.
        Type Parameters:
        T - This should be set to the return type of this method. By passing the expecred return-type class, you may conveniently avoid having to cast the returned instance, or worry about suppressing compiler warnings.
        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 Parameter syntax. Variable-Type Parameter <T> may be any Java class at all (as long as it is Serializable).

        Generally, the easiest way to obtain an instance of Class<T> is to just cite the field '.class' which is actually a member of every java.lang.Object instance!. For instance, if a user were intending to read a TreeSet from disk, all he or she needs to do is pass TreeSet.class to this parameter.

        Run-Time Generic Erasure: Generally because of the concept known as "Generic Erasure" - Variable-Type Parametrized Methods in Java have a minor 'stipulation' to keep in mind. Reading a Serialized-Object from a Data-File using this method should work great.

        However, if reading, say - an instance of Vector<String> - the user needs to keep in mind that the stated Return-Type of this method identified by parameter 'c' is not capable of expressing the Generic-Type 'String' to this method at Run-Time. This is because Generic-Type information is always 'ERASED' by the JRE at Run-Time.

        If Vector.class is passed to parameter 'c', this method will be returning the Raw-Type Vector, and your code will therefore need to cast the Returned-Value to Vector<String> to avoid the Java-Compiler's "Raw-Type Warnings."

        However, this cast will produce an "Unchecked Cast Warning" - and that means adding the very common @SuppressWarnings("unchecked") Annotation. Notice in the example below how the Vector.class parameter, itself, is insufficient to specify the return of a a Vector<String>, but using a cast and a SuppressWarnings-Annotation does the trick?

        Example:
        // 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>) which has a generic-type parameter which IS NOT included information
        // inside the class 'Vector.class'
        
        @SuppressWarnings("unchecked")
        Vector<String> myData2 = (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>' generic-parameter notation (greater-than and less-than 
        // symbols)...
        // 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")
        Vector<String> myData3 = (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:
         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
        
        Convenience Method
        Invokes: readAllObjects(Class, Collection, String, boolean)
        Passes: Object.class to 'objType'
        Passes: Newly instantiated Vector<Object> to 'collection'
        Code:
        Exact Method Body:
         return readAllObjects(Object.class, new Vector<Object>(), 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.
        Type Parameters:
        T - This allows the programmer to inform this method what type of Object's are stored in the Serialized Object File, specified by 'fName'.
        U - Merely for convenience, this method returns the Collection instance that is passed (by parameter 'Collection') as a result of this function. Therefore, the Type Parameter 'U' identifies the Return Type of this method.
        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:
        // 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:
         // Temporary Variable, used in both versions of this method
         Object o;
        
         // These stream's are 'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException and ClassNotFoundException will still be thrown out of this
         //       method if they occur.  They are not caught!
         //
         // ALSO: In try-with-resources blocks, if there is a problem/exception, these
         //       classes are all (automatically) closed/flushed, in reverse order.
        
         if (ZIP)
        
             try (
                 FileInputStream     fis = new FileInputStream(fName);
                 GZIPInputStream     gis = new GZIPInputStream(fis);
                 ObjectInputStream   ois = new ObjectInputStream(gis);
             )
             {  
                 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) { }
        
         else
        
             try (
                 FileInputStream     fis = new FileInputStream(fName);
                 ObjectInputStream   ois = new ObjectInputStream(fis);
             )
             {  
                 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) { }
        
         return collection;
        
      • 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.
        Type Parameters:
        T - This parameter informs this method what type of Serialized Objects are saved within 'fName'. The Java Stream that is returned as a result of this method will have the type Stream<T>.
        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:
         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.

        Serializable Collections:
        When multiple java.lang.Object's need to be stored, it is very-often more advisable to first save those objects to one of Java's many java.util.Collection's or java.util.List's classes. Saving Serializable-Objects to a Collection or List, first, makes the code for writing of all of those objects, simultaneously, to disk look much more elegant and much cleaner / easier to read.

        Keep in mind that all of Java's 'java.util.*' Generic Data-Structure classes implement the Serializable interface, so writing / serializing an entire Vector (for instance) is extremely simple.

        The classes that you are trying to write to disk must also be serializable, although even if they haven't been declared serializable, explicitly, in your code, the JRE will still make an attempt to serialize them anyway using its best efforts.

        In summary, it is usually wiser to use the method writeObjectToFile(...) to write a single Java-Collection, than this method.

        The following example loads the contents of an International Web-Site from Europe, and parses the HTML received into Vectorized-HTML. This output is then written to disk, and it is also written (again) as a B64 MIME-Encode String and written.

        Then this String is re-loaded and written out as HTML a second time to verify and ensure that no information was lost during the conversion of a Java 'POJO' into MIME-Encoded text.

        Example:
            // 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")
            Vector<HTMLNode> html2 = (Vector<HTMLNode>>)
                FileRW.readObjectFromTextFile("myFile.txt", html.getClass());
        
            // Re-write the loaded HTML
            FileRW.writeFile(Util.pageToString(html2), "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:
         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

        Serializable Collections:
        When multiple java.lang.Object's need to be stored, it is very-often more advisable to first save those objects to one of Java's many java.util.Collection's or java.util.List's classes. Saving Serializable-Objects to a Collection or List, first, makes the code for writing of all of those objects, simultaneously, to disk look much more elegant and much cleaner / easier to read.

        Keep in mind that all of Java's 'java.util.*' Generic Data-Structure classes implement the Serializable interface, so writing / serializing an entire Vector (for instance) is extremely simple.

        The classes that you are trying to write to disk must also be serializable, although even if they haven't been declared serializable, explicitly, in your code, the JRE will still make an attempt to serialize them anyway using its best efforts.

        In summary, it is usually wiser to use the method writeObjectToFile(...) to write a single Java-Collection, than this method.
        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:
         return StringParse.b64MimeStrToObj(loadFileToString(fileName));
        
      • 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

        Serializable Collections:
        When multiple java.lang.Object's need to be stored, it is very-often more advisable to first save those objects to one of Java's many java.util.Collection's or java.util.List's classes. Saving Serializable-Objects to a Collection or List, first, makes the code for writing of all of those objects, simultaneously, to disk look much more elegant and much cleaner / easier to read.

        Keep in mind that all of Java's 'java.util.*' Generic Data-Structure classes implement the Serializable interface, so writing / serializing an entire Vector (for instance) is extremely simple.

        The classes that you are trying to write to disk must also be serializable, although even if they haven't been declared serializable, explicitly, in your code, the JRE will still make an attempt to serialize them anyway using its best efforts.

        In summary, it is usually wiser to use the method writeObjectToFile(...) to write a single Java-Collection, than this method.

        The following example loads the contents of an International Web-Site from Europe, and parses the HTML received into Vectorized-HTML. This output is then written to disk, and it is also written (again) as a B64 MIME-Encode String and written.

        Then this String is re-loaded and written out as HTML a second time to verify and ensure that no information was lost during the conversion of a Java 'POJO' into MIME-Encoded text.

        Example:
            // 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")
            Vector<HTMLNode> html2 = (Vector<HTMLNode>>)
                FileRW.readObjectFromTextFile("myFile.txt", html.getClass());
        
            // Re-write the loaded HTML
            FileRW.writeFile(Util.pageToString(html2), "myFile2.html");
        
            // NOTE: Using UNIX "diff -s myFile1.html myFile2.html" produces this:
            // Files myFile1.html and myFile2.html are identical
        
        Type Parameters:
        T - This Type Parameter informs this method what type of Base-64 Serialized Object is saved within Text File 'fileName'. The returned result of this method will have this type, for convenience to avoid casting the Object (unless that Object is a Java Generic, and you wish to avoid a "Raw Types" warning. See further details inside the explanation about parameter 'c').
        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 Parameter syntax. Variable-Type Parameter <T> may be any Java class at all (as long as it is Serializable).

        Generally, the easiest way to obtain an instance of Class<T> is to just cite the field '.class' which is actually a member of every java.lang.Object instance!. For instance, if a user were intending to read a TreeSet from disk, all he or she needs to do is pass TreeSet.class to this parameter.

        Run-Time Generic Erasure: Generally because of the concept known as "Generic Erasure" - Variable-Type Parametrized Methods in Java have a minor 'stipulation' to keep in mind. Reading a Serialized-Object from a Data-File using this method should work great.

        However, if reading, say - an instance of Vector<String> - the user needs to keep in mind that the stated Return-Type of this method identified by parameter 'c' is not capable of expressing the Generic-Type 'String' to this method at Run-Time. This is because Generic-Type information is always 'ERASED' by the JRE at Run-Time.

        If Vector.class is passed to parameter 'c', this method will be returning the Raw-Type Vector, and your code will therefore need to cast the Returned-Value to Vector<String> to avoid the Java-Compiler's "Raw-Type Warnings."

        However, this cast will produce an "Unchecked Cast Warning" - and that means adding the very common @SuppressWarnings("unchecked") Annotation. Notice in the example below how the Vector.class parameter, itself, is insufficient to specify the return of a a Vector<String>, but using a cast and a SuppressWarnings-Annotation does the trick?

        Example:
        // 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>) which has a generic-type parameter which IS NOT included information
        // inside the class 'Vector.class'
        
        @SuppressWarnings("unchecked")
        Vector<String> myData2 = (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>' generic-parameter notation (greater-than and less-than 
        // symbols)...
        // 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")
        Vector<String> myData3 = (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:
         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:
         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:
         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 a directory that exists, this method will throw a FileNotFoundException.

        This can be avoided, however, by passing TRUE to parameter 'createDirsIfNotExist'. If 'outFileOrDirName' specifies a directory (by virtue of the fact that it ends with the File.separator String) - and 'createDirsIfNotExist' is TRUE, then this method will first create any and all sub-directories needed using the standard Java's File.mkdirs() method before copying the file.

        SUMMARY: The programmer may provide either a Directory-Name or a File-Name to parameter 'outFileOrDirName'. If a Directory-Name was provided, the moved file will keep its name - having the same name as the original file, ('inFileName') had (but have been copied to directory '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:
         File f = new File(outFileOrDirName);
        
         if (createDirsIfNotExist) if (! f.exists()) 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(); }
        
      • 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-Then: deletes
        Code:
        Exact Method Body:
         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

        Platform Independance (WORA):
        If this method is invoked from a UNIX or LINUX platform, then it will, generally, bring about identical results as a call to Shell.RM(String, String) where the UNIX "-r" (recursive) flag has been included / set. On such a platform, an entire directory would be eliminated.

        However, if executed from Windows, the class Shell would fail since it only works on UNIX, but this method here would still succeed at its task. It is a "Platform-Independent" function.
        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 expects an implementation of Java's java.lang.Appendable interface 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.StorageWriter Sends text to System.out, and saves it, internally.
        FileWriter, PrintWriter, StringWriter General purpose java text-output classes
        FileOutputStream, PrintStream More general-purpose java text-output classes

        Checked IOException:
        The Appendable interface requires that the Checked-Exception IOException be caught when using its append(...) 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:
         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') please pass TRUE to the parameter 'hasCommasInInts'.

        File-Format:
        The Formatting-Requirements of the file aren't very particular. The 'flag' parameter 'isCSV' merely explains whether or not the individual integers in the file are separated by commas.

        Each line of the file may have any number of such int's on a particular line. The file may also have any number of such int-containing lines. Blank lines found within the input file will are simply ignored.

        If parameter 'isCSV' is passed FALSE, each number in the file should be separated by some amount (at least one character) of White-Space. Multiple numbers may still be placed on a single line - as long as there is White-Space between them).

        If 'isCSV' is passed TRUE, then each int must be separated by a comma character.

        Number-Format:
        The numbers in this Text-File must be parse-able by Java class java.lang.Integer via its 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:
         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-Requirements of the file aren't very particular. The 'flag' parameter 'isCSV' merely explains whether or not the individual integers in the file are separated by commas.

        Each line of the file may have any number of such long's on a particular line. The file may also have any number of such long-containing lines. Blank lines found within the input file will are simply ignored.

        If parameter 'isCSV' is passed FALSE, each number in the file should be separated by some amount (at least one character) of White-Space. Multiple numbers may still be placed on a single line - as long as there is White-Space between them).

        If 'isCSV' is passed TRUE, then each long must be separated by a comma character.

        Number-Format:
        The numbers in this Text-File must be parse-able by Java class 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:
         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-Requirements of the file aren't very particular. The 'flag' parameter 'isCSV' merely explains whether or not the individual integers in the file are separated by commas.

        Each line of the file may have any number of such long's on a particular line. The file may also have any number of such long-containing lines. Blank lines found within the input file will are simply ignored.

        If parameter 'isCSV' is passed FALSE, each number in the file should be separated by some amount (at least one character) of White-Space. Multiple numbers may still be placed on a single line - as long as there is White-Space between them).

        If 'isCSV' is passed TRUE, then each long must be separated by a comma character.

        Number-Format:
        The numbers in this Text-File must be parse-able by Java class 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:
         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();
        
      • writeBinary

        🡅  🡇     🗕  🗗  🗖
        public static void writeBinary​(byte[] bArr,
                                       java.lang.String fileName)
                                throws java.io.IOException
        Convenience Method
        Invokes: java.io.FileOutputStream.write(byte[]).
        NOTE: This may throw IOException, FileNotFoundException, etc...
        Code:
        Exact Method Body:
         // The input-stream is  'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!  This also (potentially) throws SecurityException & FileNotFoundException
        
         try
             (FileOutputStream fos = new FileOutputStream(fileName))
             { fos.write(bArr); }
        
      • writeBinary

        🡅  🡇     🗕  🗗  🗖
        public static void writeBinary​(byte[] bArr,
                                       int offset,
                                       int len,
                                       java.lang.String fileName)
                                throws java.io.IOException
        Convenience Method
        Invokes: java.io.FileOutputStream.write(byte[], int, int).
        NOTE: This may throw IOException, IndexOutOfBoundsException, etc...
        Code:
        Exact Method Body:
         // The input-stream is  'java.lang.AutoCloseable'.
         //
         // NOTE: The IOException will still be thrown out of this method if it occurs.  It is not
         //       caught!  This also (potentially) throws SecurityException, FileNotFoundException,
         //       IndexOutOfBoundsExcepton (if 'offset' or 'len' do not adhere to 'bArr' definition)
        
         try
             (FileOutputStream fos = new FileOutputStream(fileName))
             { fos.write(bArr, offset, len); }
        
      • readBinary

        🡅  🡇     🗕  🗗  🗖
        public static byte[] readBinary​(java.lang.String fileName,
                                        int offset,
                                        int len)
                                 throws java.io.FileNotFoundException,
                                        java.io.IOException
        Reads data from a binary file into a Java byte[] array.

        Unlike Java's FileOutputStream.write(...) method, the read(...) Java provides in that same exact class is more difficult to use. This method is much longer than its corresponding writeBinary(byte[], String) method.
        Parameters:
        fileName - The name of the file (on the File-System) to read.
        offset - The number of byte's to skip before appending a byte into the output byte[] array. If the value provided to parameer 'offset' is longer than the size of the file itself, then a zero-length byte[] array will be returned.

        IMPORTANT: The meaning of the value in parameter 'offset' is very different from the meaning of a parameter by that exact same name, except in method read(...) of class FileInputStream. HERE the offset is the number of bytes to skip inside of file 'fileName', before saving the values that are read froom disk. In the FileInputStream, offset is used as an array pointer.
        len - Once the internal-loop has begun copying bytes from the Data-File into the returned byte[] array, byte's will continue to be copied into this array until precisely 'len' bytes have been copied.

        IMORTANT: The user may provide any negative number to this parameter, and the read process will simply begin at position 'offset', and continue reading until the End of the File has been reached.
        Returns:
        Returns a byte[]-array, with a length of (parameter) 'len' bytes.
        Throws:
        java.io.FileNotFoundException - Class java.io.FileInputStream will throw a FileNotFoundException if that class is passed a 'fileName' that does not exist, or is a File-Name that represents a directory not a file.
        java.lang.SecurityException - If a security manager exists and its checkRead method denies read access to the file.
        java.io.IOException - The FileInputStream instance, and the java.io.File instance are both capable of throwing IOException.
        java.lang.IllegalArgumentException -

        • The value provided to 'offset' is negative
        • The value provided to parameter 'len' is zero.
        FileSizeException - This exception throws if any of the following are detected:

        • The returned byte[] array cannot have a size larger than Integer.MAX_VALUE. If the returned array would have a larger size - based on any combination of provided input values, then this exception will throw.
        • The value provided to 'offset' is larger than the size of the underlying file that is specified by parameter 'fileName'
        • The total of offset + len is larger than the size of the underlying file.
        • An invocation of the method File.length() returns zero, indicating that the file is either unreadable, non-existant, or possibly empty.
        java.io.EOFException - This particular exception should not be expected. Before any reads are done, the size of the Data-File is first checked to see if it is big enough to have the amount of data that is requested by input paramters 'offset' and 'len'. If however, an error occurrs, and the Operating System returns an EOF earlier than expected (for unforseen reasons), then EOFException would throw.
        Code:
        Exact Method Body:
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // EXCEPTION CHECKS
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         if (offset < 0) throw new IllegalArgumentException
             ("The value of offset (" + offset + ") is negative.");
        
         if (len == 0) throw new IllegalArgumentException
             ("A value of zero was provided to parameter 'len.'  This is not allowed");
        
         File f = new File(fileName);
        
         try
             (FileInputStream fis = new FileInputStream(f))
         {
             long fileLen = f.length();
        
             // A file-name that points to a completely empty file was passed to parameter 'fileName'
             // **OR** the operating system returned 0 for some other error-related reason.
             // According to the Java-Doc explanation, a '0' returned value might mean there were
             // errors when trying to access the file.
        
             if (fileLen == 0) throw new FileSizeException(
                 "Calling java.io.File.length() returned 0 for the file-name that was " +
                 "provided to this method:\n[" + fileName + "].  This might mean that the file " +
                 "does not exist, or has other issues.",
                 0
             );
        
             // The file would end before we have even started reading bytes - after having skipped
             // 'offset' nmber of initial bytes.
        
             if (offset > fileLen) throw new FileSizeException(
                 "The value of offset (" + offset + ") is larger than the size of the binary " +
                 "file, which only had size (" + fileLen + ").",
                 fileLen
             );
        
             // If 'len' was passed a negative value, that value is actually meaningless - and was
             // just used to indicate that reading the entire file starting at byte # 'offset' is
             // what the user is requesting.
        
             if (len > 0)
        
                 // This simply checks how many bytes the file would need to have to provide for
                 // reading from 'offset' up until 'offset + len'
        
                 if ((offset + len) > fileLen) throw new FileSizeException(
                     "The file [" + fileName + "] apparently has a size of [" + fileLen + "], " +
                     "but the offset (" + offset + ") and the length (" +  len + ") that was " +
                     "requested sum to (" + (offset+len) + "), which is greater than that size.",
                     fileLen
                 );
        
        
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
             // More Exception Checks: Check what the size of the returned byte[] array will be
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
             // Negative-Length means that bytes are read until an EOF occurrs
             if (len < 0)
             {
                 long bytesToRead = fileLen - offset;
        
                 if (bytesToRead > Integer.MAX_VALUE) throw new FileSizeException(
                     "This file has [" + fileLen + "] bytes of data, and even with an offset of " +
                     '[' + offset + "], there are still " + bytesToRead + " bytes of data to " +
                     "place into the array.  This value is larger than Integer.MAX_VALUE " +
                     "(" + Integer.MAX_VALUE + ").",
                     fileLen
                 );
        
                 else len = (int) bytesToRead;
             }
        
             // A Positive length means that exactly the value inside input-parameter 'len' need to
             // be placed into the returned byte[] array.
        
             else if (len > Integer.MAX_VALUE) throw new FileSizeException(
                 "This file has [" + fileLen + "] bytes of data, which is larger than " +
                 "Integer.MAX_VALUE (" + Integer.MAX_VALUE + ").",
                 fileLen
             );
        
        
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
             // FIRST, if there is a NON-ZERO OFFSET, then exactly OFFSET bytes must be skipped
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
             int     failedReads         = 0;
             long    bytesSkipped        = 0;
             int     totalBytesSkipped   = 0;
             int     bytesRemaining      = offset;
        
             // NOTE: This loop is skipped, immediately / automatically, if indeed 'offset' is zero
             while (totalBytesSkipped < offset)
        
                 if ((bytesSkipped = fis.skip(bytesRemaining)) == 0)
                 {
                     if (failedReads++ == 10) throw new IOException(
                         "There have 10 repeated attempts to read the file's data, but all " +
                         "attempts have resulted in empty-reads with zero bytes being  retrieved " +
                         "from disk."
                     );
                 }
                 else
                 {
                     // I don't see why this should happen, but it will be left here, just in
                     // case Java screws up.
        
                     if (bytesSkipped > bytesRemaining) throw new InternalError(
                         "This error is being thrown because the Java Virtual Machine has " +
                         "skipped past the end of the requested offset.  This has occured while " +
                         "calling FileInputStream.skip(offset)."
                     );
        
                     // NOTE: I am *FULLY AWARE* this is redundant, but the variable names are
                     //       the only thing that is very readable about this method.
        
                     totalBytesSkipped += bytesSkipped;
                     bytesRemaining -= bytesSkipped;
                 }
        
        
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
             // THEN, Read the bytes from the file
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
             byte[]  retArr      = new byte[len];
             int     arrPos      = 0;
        
             // This one was already defined / declared in the previous part.  Initialize it, but
             // don't re-declare it.
             bytesRemaining = len;
        
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
             // This loop exits when all (requested) bytes have been read, or EOFException!
             // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
             while (bytesRemaining > 0)
             {
                 int bytesRead = fis.read(retArr, arrPos, bytesRemaining);
        
        
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 // Case 1: The EOF Marker was reached, before filling up the response-array
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
                 if (bytesRead == -1) if (bytesRemaining > 0) throw new EOFException(
                     "The end of file '" + fileName + "' was reached before " + len +
                     " bytes were read.  Only " + arrPos + " bytes were read."
                 );
        
        
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 // Yes, this seems redundant, but it's just the way it is
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 // 
                 // arrPos           ==>  0 ... retArr.length (retArr.length => input-param 'len')
                 // bytesRemaining   ==>  'len' ... 0
        
                 arrPos          += bytesRead;
                 bytesRemaining  -= bytesRead;
        
        
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 // Case 2: Exactly the appropriate number of bytes were read.
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
                 if (arrPos == retArr.length) return retArr;
        
        
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 // Case 3: This should not be reachable!
                 // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
                 //
                 // Java's FileInputStream.read method is supposed to stop when it has read
                 // 'bytesRemaining' number of bytes!
        
                 if (arrPos > retArr.length) throw new UnreachableError();
             }
        
             // One of the cases inside the loop body must fire before the loop ever actually exits,
             // unless I'm missing something!
             throw new UnreachableError();
         }
        
      • readClass

        🡅     🗕  🗗  🗖
        public static java.lang.Class<?> readClass​
                    (java.lang.String classFileName,
                     java.lang.String... possibleClassNames)
                throws java.io.IOException
        
        Attempts to read a java.lang.Class from a class-file.

        It is not neccessarily always knownst to the programmer what the Full-Package Class-Name of the class that's inside the class-file actually is.
        Parameters:
        classFileName - The name of any class-file on the File-System.
        possibleClassNames - If the exact Full-Package Name of the class being read is known, then that ought to be the only String passed to this Var-Args String-Parameter. If there are multiple possibilities, pass all of them, and all we be used in an attempt to parse & load this class.

        DEVELOPER NOTE: Perhaps I am stupid, but I cannot find any way to read a class file, and then ask that class-file either:

        • What the name of the Class in the Class-File is?
        • What the name of the Package being used in that Class-File is?


        So, for now, a Var-Args String-Array is required.

        To add insult to injury, the standard Java Exception class 'TypeNotPresentException' doesn't have a constructor that accepts a 'message' parameter (it accepts a 'typeName') parameter instead. As a result, if this method throws that exception, the error-message printed has a few 'extranneous characters' BOTH before the actual message, AND after it. It is staying this way because Java's Description of that exception matches precisely with its use here.
        Returns:
        An instance of java.lang.Class that was contained by the Class-File.
        Throws:
        java.io.IOException - Java may throw several exceptions while attempting to load the '.class' file into a byte[] array. Such exceptions may include IOException, SecurityException, FileNotFoundException etc...
        java.lang.TypeNotPresentException - If none of the names listed in Var-Args String[] Array parameter 'possibleClassNames' are consistent with BOTH the package-name AND the class-name of the actual class that resides inside 'classFileName', then this exception will throw.

        NOTE: Rather than simply returning 'null', this RuntimeException is thrown as a nicely worded error message is provided.
        Code:
        Exact Method Body:
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Load the entire '.class' file into a byte[] array.
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         // Now read the bytes directly into a byte[] array, courtesy of Torello.Java.FileRW
         byte[] byteArray = readBinary(classFileName);
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Create a ClassLoader - and convert "byte[]" into "Class<?> summarySorterClass"
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         // NOTE: The commented lines below will not work if there is a "Package Name" given to the
         //       class (in the '.java' file).  It is better to just read the raw class-file bytes 
         //       into a Java byte[] array.  SPECIFICALLY, if class is not inside of a directory
         //       that is PRECISELY-CONSISTENT with the full-path package+class name, then the class
         //       loader listed below will FAIL.  (NOTE: If the package+class name is consisten,
         //       then a programmer wouldn't need ANY OF THIS, and could simply call the normal
         //       "Class.forName(fullPackageClassName)" to get the class!)
         //
         // ClassLoader cl = new URLClassLoader(new URL[] { new URL("file://" + path) });
         // Class<?> ret = cl.loadClass(className);
         //
         // HOWEVER: Creating a new ClassLoader instance that accepts the byte-array (thereby
         //          exporting the 'protected' method defineClass) *DOES* work.
        
         class ByteClassLoader extends ClassLoader
         {
             public Class<?> defineClass(String name, byte[] classBytes)
             { return defineClass(name, classBytes, 0, classBytes.length); }
         }
        
         ByteClassLoader cl  = new ByteClassLoader();
         Class<?>        ret = null;
         StringBuilder   sb  = new StringBuilder();
        
        
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
         // Make attempts to convert the byte[] array into a java.lang.Class
         // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        
         for (String fullClassName : possibleClassNames)
        
             try
                 { return cl.defineClass(fullClassName, byteArray); }
        
             catch (NoClassDefFoundError e)
             {
                 String errorMessage = e.getMessage();
        
                 if (errorMessage != null) sb.append(errorMessage + '\n');
             }
        
         throw new TypeNotPresentException(
             "The Class-File: [" + classFileName  + "] seems to have been successfully read, but " +
             "none of the user provided Canonical-Class Names (including a package) were " +
             "consistent with the actual name of the Class/Type inside that class file.  Below " +
             "are listed the exception-messages received, which include both the actual/complete " +
             "canonical class-name, along with your user-provided guesses.  Errors Saved:\n" +
             StrIndent.indent(sb.toString(), 4),
             null
         );