Package Torello.Java
Class FileRW
- java.lang.Object
-
- Torello.Java.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 methodFileRW.appendToFilefor instance, opens the File-Pointer, writes theString-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 methodFileRW.writeObjectToFilefor 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.
Hi-Lited Source-Code:- View Here: Torello/Java/FileRW.java
- Open New Browser-Tab: Torello/Java/FileRW.java
File Size: 97,608 Bytes Line Count: 2,105 '\n' Characters Found
Stateless Class:This class neither contains any program-state, nor can it be instantiated. The@StaticFunctionalAnnotation may also be called 'The Spaghetti Report'.Static-Functionalclasses are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@StatelessAnnotation.
- 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
-
-
Field Summary
Fields Modifier and Type Field static booleanTRUNCATE_EOF_CHARS
-
Method Summary
Read Text-Files Modifier and Type Method static <T extends Collection<String>>
TloadFileToCollection(T collectionChoice, String fName, boolean includeNewLine)static Stream<String>loadFileToStream(String fName, boolean includeNewLine)static StringloadFileToString(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 voidwriteFile(CharSequence s, String fName)static voidwriteFile(Iterable<String> i, String fName)static voidwriteFile_NO_NEWLINE(Iterable<String> i, String fName)Append Text to Text-Files Modifier and Type Method static voidappendToFile(CharSequence s, String fName)static voidappendToFile(Iterable<String> i, String fName, boolean addNewLines)Read a Single Serialized-Object from a File Modifier and Type Method static ObjectreadObjectFromFile(String fName, boolean ZIP)static <T> TreadObjectFromFile(String fName, Class<T> c, boolean ZIP)static ObjectreadObjectFromFileNOCNFE(String fName, boolean ZIP)static <T> TreadObjectFromFileNOCNFE(String fName, Class<T> c, boolean ZIP)static ObjectreadObjectFromTextFile(String fileName)static <T> TreadObjectFromTextFile(String fileName, Class<T> c)static <T> TreadObjectFromTextFileNOCNFE(String fileName, Class<T> c)Write a Single Serialized-Object to a File Modifier and Type Method static voidwriteObjectToFile(Object o, String fName, boolean ZIP)static booleanwriteObjectToFileNOCNFE(Object o, String fName, boolean ZIP)static voidwriteObjectToTextFile(Object o, String fileName)Read Multiple Serialized-Objects from a File Modifier and Type Method static <T,
U extends Collection<T>>
UreadAllObjects(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 voidwriteAllObjectsToFile(Iterable<?> i, String fName, boolean ZIP)static booleanwriteAllObjectsToFileNOCNFE(Iterable<?> i, String fName, boolean ZIP)Serialized Object I/O Stream Modifier and Type Method static ObjectInputStreamgetOIS(String fName, boolean ZIP)static ObjectOutputStreamgetOOS(String fName, boolean ZIP)Move, Copy & Delete Modifier and Type Method static voidcopyFile(String inFileName, String outFileOrDirName, boolean createDirsIfNotExist)static voiddeleteFiles(String... fileNames)static intdelTree(String directoryName, boolean reCreateDirectoryOnExit, Appendable log)static voidmoveFile(String inFileName, String outFileName, boolean createDirsIfNotExist)Read Text-Numbers Modifier and Type Method static DoubleStreamreadDoublesFromFile(String fileName, boolean hasCommasInDoubles, boolean isCSV)static IntStreamreadIntsFromFile(String fileName, boolean hasCommasInInts, boolean isCSV, int radix)static LongStreamreadLongsFromFile(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 voidwriteBinary(byte[] bArr, int offset, int len, String fileName)static voidwriteBinary(byte[] bArr, String fileName)
-
-
-
Field Detail
-
TRUNCATE_EOF_CHARS
public static boolean TRUNCATE_EOF_CHARS
This is used by methodloadFileToString(String). By default this flag is set toTRUE, and when it is, any trailingEOF chars, ASCII-0found in a file that is to be interpreted as a Text-File, will be truncated from theStringreturned by that'reader'method.- Code:
- Exact Field Declaration Expression:
public static boolean TRUNCATE_EOF_CHARS = true;
-
-
Method Detail
-
writeFile
public static void writeFile(java.lang.CharSequence s, java.lang.String fName) throws java.io.IOException
Writes the entire contents of a singlejava.lang.Stringto a file on the File-System named'fName'.Writeable Directory: Though the file does not need to already exist (at the time this method is invoked) 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 else a JavaIOExceptionwill be thrown.- Parameters:
s- Ajava.lang.Stringwhich is appended, in entirety, to the file ('fName')fName- The name of the file to which the contents of thejava.lang.Stringare 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 anIterable<String>, and a filename, and writes eachjava.lang.Stringin theIteratorthat it produces to the file specified by File-Name parameter'fName'Writeable Directory: Though the file does not need to already exist (at the time this method is invoked) 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 else a JavaIOExceptionwill be thrown.New-Line Characters: A newline('\n')is appended to the end of eachjava.lang.Stringbefore writing it to the file.- Parameters:
i- This is any javaIterable<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 thejava.lang.Stringare 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 anIterableof String, and a filename and writes eachjava.lang.Stringin theIteratorthat it produces to the file specified by File-Name parameter'fName'Writeable Directory: Though the file does not need to already exist (at the time this method is invoked) 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 else a JavaIOExceptionwill be thrown.New-Line Characters: In this function a newline('\n')character is not appended to the end of eachjava.lang.Stringof the inputIterator.- 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 thejava.lang.Stringare 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 inputjava.lang.String- actually ajava.lang.CharSequenceto 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- Ajava.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 thejava.lang.Stringare 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 anIterable<String>, and a filename, and appends eachjava.lang.Stringin theIteratorthat 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 javaIterable<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 thejava.lang.Stringare appended. If This file doesn't already exist, it is created here.addNewLines- When this parameter is passedTRUE, a New-Line character will be appended after eachStringthat is written. WhenFALSE, only theString'sproduced by theIterable, 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 singlejava.lang.StringTrailing Zeros: Some of the ugliest code to see is that which scans for'EOF'characters that have been 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 trailingASCII-0characters (literally,char c == 0) from the files that are read.
Finding'.html'or'.java'files in which some editor (for whatever reason) has insertedEOF-likecharacters to the end of the text can make programming a headache.
Suffice it to say, theStringthat 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'sin them.Static Boolean-Flag: This class (classFileRW) has astatic, booleanflag that is able to prevent / shunt this 'Trailing Zero Removing' behavior. WhenTRUNCATE_EOF_CHARSis set toFALSE, reading a file into aStringusing this method will return theString- 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>intoString[]- 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 JavaStreaminstance.- Parameters:
fName- A File-Name of a valid Text-File in the File-System.includeNewLine- if this isTRUE, a'\n'(newline/CRLF) is appended to the end of eachjava.lang.Stringread from this file. If not, the original newline characters which occur in the file, will be eliminated.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 aStream<String>that is identical to the original file. However, if the final character in the file is not a new-line'\n', then theStream<String>that is returned will have an extra new-line appended to the lastStringin theStream, and the resultantStream<String>will be longer than the original file by 1 character.- Returns:
- The entire contents of the file as a series of
java.lang.Stringcontained by ajava.util.stream.Stream<String>. Converting JavaStream'sto 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(); }
-
loadFileToVector
public static java.util.Vector<java.lang.String> loadFileToVector (java.lang.String fName, boolean includeNewLine) throws java.io.IOException
Convenience Method
Invokes:loadFileToCollection(Collection, String, boolean)
Passes: Newly instantiatedVector<String>to'collectionChoice'- Code:
- Exact Method Body:
return loadFileToCollection(new Vector<String>(), fName, includeNewLine);
-
loadFileToCollection
public static <T extends java.util.Collection<java.lang.String>> T loadFileToCollection (T collectionChoice, java.lang.String fName, boolean includeNewLine) throws java.io.IOException
This method loads the contents of a file to ajava.util.Collection<String>object, where eachjava.lang.Stringin the output / returnedCollectionis 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").split('\n')
Variable-Type Parameter: This method uses Java's Variable-Type Parameter syntax to allow the programmer to decide what type ofCollection<String>they would like returned from this method. Common examples would includeVector<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 JavaString-Collectionwhich is is identical to the original file.
However, if the final character in the file is not a new-line'\n'character, then the returnedCollectionwill have an extra new-line appended immediately after the lastStringin theCollection. Furthermore, the resultantCollection<String>will be longer than the original file by 1 character.- Type Parameters:
T- This may be any class which extendsjava.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 baseclass Collection<String>- using'String'as the generic-type parameter. It will be populated with the lines from a Text-File using theCollection.add(String)method.fName- the File-Name of a valid Text-File on the File-System.includeNewLine- if this isTRUE, a'\n'(newline/CRLF) is appended to the end of eachjava.lang.Stringread 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;
-
writeObjectToFileNOCNFE
public static boolean writeObjectToFileNOCNFE(java.lang.Object o, java.lang.String fName, boolean ZIP) throws java.io.IOException
- Code:
- Exact Method Body:
try { writeObjectToFile(o, fName, ZIP); return true; } catch (ClassNotFoundException cnfe) { return false; }
-
writeObjectToFile
public static void writeObjectToFile(java.lang.Object o, java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Writes ajava.lang.Objectto a file for storage, and future reference.Writeable Directory: Though the file does not need to already exist (at the time this method is invoked) 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 else a JavaIOExceptionwill be thrown.- Parameters:
o- AnObjectto be written to a file as a "Serializable"java.lang.ObjectfName- The name of the output fileZIP- a boolean that, whenTRUE, 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); }
-
writeAllObjectsToFileNOCNFE
public static boolean writeAllObjectsToFileNOCNFE(java.lang.Iterable<?> i, java.lang.String fName, boolean ZIP) throws java.io.IOException
- Code:
- Exact Method Body:
try { writeAllObjectsToFile(i, fName, ZIP); return true; } catch (ClassNotFoundException cnfe) { return false; }
-
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 ofjava.lang.Objectto a file for storage, and future reference.
Serializable Collections:
When multiplejava.lang.Object'sneed to be stored, it is very-often more advisable to first save those objects to one of Java's manyjava.util.Collection'sorjava.util.List'sclasses. SavingSerializable-Objects to aCollectionorList, 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 theSerializableinterface, so writing / serializing an entireVector(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 methodwriteObjectToFile(...)to write a single Java-Collection, than this method.Writeable Directory: Though the file does not need to already exist (at the time this method is invoked) 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 else a JavaIOExceptionwill be thrown.- Parameters:
i- A series,Collection, orListofObject'sto be written to a file in Serializable format.fName- The name of the output fileZIP- abooleanthat, whenTRUE, will cause theObject'sdata 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 theCLASSPATH.- 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()); }
-
readObjectFromFileNOCNFE
public static java.lang.Object readObjectFromFileNOCNFE (java.lang.String fName, boolean ZIP) throws java.io.IOException
- Code:
- Exact Method Body:
try { return readObjectFromFile(fName, ZIP); } catch (ClassNotFoundException cnfe) { return null; }
-
readObjectFromFile
public static java.lang.Object readObjectFromFile (java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Reads anObjectfrom a Data-File which must contain a serializedjava.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 multiplejava.lang.Object'sneed to be stored, it is very-often more advisable to first save those objects to one of Java's manyjava.util.Collection'sorjava.util.List'sclasses. SavingSerializable-Objects to aCollectionorList, 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 theSerializableinterface, so writing / serializing an entireVector(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 methodwriteObjectToFile(...)to write a single Java-Collection, than this method.- Parameters:
fName- The name of a Data-File that contains a serializedjava.lang.ObjectZIP- if this isTRUE, it is assumed that the Data-File contains a Zip-CompressedObject- Returns:
- The
Objectthat 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 theCLASSPATH.- 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(); }
-
readObjectFromFileNOCNFE
public static <T> T readObjectFromFileNOCNFE(java.lang.String fName, java.lang.Class<T> c, boolean ZIP) throws java.io.IOException
- Code:
- Exact Method Body:
try { return readObjectFromFile(fName, c, ZIP); } catch (ClassNotFoundException cnfe) { return null; }
-
readObjectFromFile
public static <T> T readObjectFromFile(java.lang.String fName, java.lang.Class<T> c, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Reads anObjectfrom a Data-File which must contain a serializedjava.lang.Object.
Serializable Collections:
When multiplejava.lang.Object'sneed to be stored, it is very-often more advisable to first save those objects to one of Java's manyjava.util.Collection'sorjava.util.List'sclasses. SavingSerializable-Objects to aCollectionorList, 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 theSerializableinterface, so writing / serializing an entireVector(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 methodwriteObjectToFile(...)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 serializedjava.lang.Objectc- This is the type of theObjectexpecting to be read from disk. A value for this parameter can always be obtained by referencing thestaticfield'.class'which is attached to every object in java.The parameterClass lt;T> cspecifies the expected runtime type of theObjectread from the file. This enables the method to return a correctly typed reference of typeT. 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 ofClass<T>is to just cite the field'.class'which which is a static member present within everyclass-Type in Java. For instance, if a user were intending to read aTreeSetfrom disk, all he or she needs to do is passTreeSet.classto this parameter.Run-Time Generic Erasure: Due to Java's type-erasure model, Generic Type-Parameters like<String>are not preserved at runtime. As a result, this method cannot determine the specific type parameter of generic types — only their raw class. Despite this, for most practical cases - especially single non-generic objects, this method should work exactly as expected.
However, if reading, say - an instance ofVector<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.
IfVector.classis passed to parameter'c', this method will be returning the Raw-TypeVector, and your code will therefore need to cast the Returned-Value toVector<String>to avoid the Java-Compiler's "Raw-Type Warnings." Again, this cast is necessary becauseVector.classalone does not actually "carry" or "contain" the Generic-Type information -<String>
However, and lastly, this cast will produce an "Unchecked Cast Warning" - and that means adding the very-commonly-used@SuppressWarnings("unchecked")Annotation. Notice in the example below how theVector.classparameter, itself, is insufficient for specifying the return of aVector<String>. However, using a cast and a SuppressWarnings annotation resolves the issue cleanly.
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);
Note Regarding Data: If the file being read did not actually have aVectorcontaining onlyString-instances. This may result in "Heap Pollution" — which is a state where type safety is violated at runtime due to unchecked Generic-Casts.ZIP- if this isTRUE, it is assumed that the Data-File contains a Zip-CompressedObject- Returns:
- The
Objectthat 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 theCLASSPATH.- 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.classto'objType'
Passes: Newly instantiatedVector<Object>to'collection'- Code:
- Exact Method Body:
return readAllObjects(Object.class, new Vector<Object>(), fName, ZIP);
-
readAllObjectsToVector
public static <T> java.util.Vector<T> readAllObjectsToVector (java.lang.Class<T> objType, java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Convenience Method
Invokes:readAllObjects(Class, Collection, String, boolean)
Passes: Newly instantiatedVector<T>to'collection'- Code:
- Exact Method Body:
return readAllObjects(objType, new Vector<T>(), fName, ZIP);
-
readAllObjects
public static <T,U extends java.util.Collection<T>> U readAllObjects (java.lang.Class<T> objType, U collection, java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Reads allObject'sfound inside a Data-File. This Data-File should contain only java-serializedjava.lang.Object's.- Type Parameters:
T- This allows the programmer to inform this method what type ofObject'sare stored in the Serialized Object File, specified by'fName'.U- Merely for convenience, this method returns theCollectioninstance 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 theObject'sthat the user is expecting to read from disk. A value for this parameter can always be obtained by referencing thestaticfield'.class'which is attached to everyObject / Classin java. For instance, to read a data-file containing a series ofjava.lang.Integerinstances, useInteger.classas 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 desiredCollection<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 serializedObject'sZIP- if this isTRUE, it is assumed that the Data-File contains Zip-Compressed objects- Returns:
- A reference to the
Collectionthat 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 java.util.stream.Stream<java.lang.Object> readAllObjectsToStream (java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Convenience Method
Invokes:readAllObjectsToStream(Class, String, boolean)
Passes:Object.classto'objType'- Code:
- Exact Method Body:
return readAllObjectsToStream(Object.class, fName, ZIP);
-
readAllObjectsToStream
public static <T> java.util.stream.Stream<T> readAllObjectsToStream (java.lang.Class<T> objType, java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Reads all objects found inside a Data-File. This Data-File should contain only java-serializedObject's.- Type Parameters:
T- This parameter informs this method what type of Serialized Objects are saved within'fName'. The JavaStreamthat is returned as a result of this method will have the typeStream<T>.- Parameters:
fName- The name of a Data-File that contains the serializedObject'sobjType- This is the type of theObject'sexpecting to be read from disk. A value for this parameter can always be obtained by referencing the static field'.class'which is attached to everyObjectin Java. For instance, to read a Data-File containing a series ofDateinstances, useDate.classas the value to pass to this parameter.ZIP- if this isTRUE, it is assumed that the Data-File contains Zip-CompressedObject's- Returns:
- A
Stream<T>of allObject'sfound in the Data-File. Converting JavaStream'sto 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; try( FileInputStream fis = new FileInputStream(fName); ObjectInputStream ois = ZIP ? new ObjectInputStream(new GZIPInputStream(fis)) : new ObjectInputStream(fis); ) { 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) { } return b.build();
-
writeObjectToTextFile
public static void writeObjectToTextFile(java.lang.Object o, java.lang.String fileName) throws java.io.IOException
Uses Java'sObjectserialization mechanism to serialize ajava.lang.Object, and then uses theBase64 String-MIME Encodingsystem, also provided by java, to convert theObjectinto a text-safejava.lang.Stringthat may be viewed, e-mailed, written to a web-page, etc.
Serializable Collections:
When multiplejava.lang.Object'sneed to be stored, it is very-often more advisable to first save those objects to one of Java's manyjava.util.Collection'sorjava.util.List'sclasses. SavingSerializable-Objects to aCollectionorList, 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 theSerializableinterface, so writing / serializing an entireVector(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 methodwriteObjectToFile(...)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 aB64 MIME-Encode Stringand written.
Then thisStringis 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'intoMIME-Encodedtext.
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 serializablejava.lang.Objectinstance. It will be written to a Text-File after first serializing theObject, and then next converting the serialized data-bits to MIME-safe encoded text.fileName- The fileName that will be used to save thisObjectas a Text-File.- Throws:
java.io.IOException- See Also:
writeFile(CharSequence, String),StringParse.objToB64MimeStr(Object)- 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-Safejava.lang.Stringfrom a text file and return theObjectthat it represented
Serializable Collections:
When multiplejava.lang.Object'sneed to be stored, it is very-often more advisable to first save those objects to one of Java's manyjava.util.Collection'sorjava.util.List'sclasses. SavingSerializable-Objects to aCollectionorList, 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 theSerializableinterface, so writing / serializing an entireVector(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 methodwriteObjectToFile(...)to write a single Java-Collection, than this method.- Parameters:
fileName- The name of the file containing the MIME-Encoded Serializedjava.lang.Object.- Returns:
- The
Objectthat had been encoded into the Text-File. - Throws:
java.io.IOException- See Also:
loadFileToString(String),StringParse.b64MimeStrToObj(String)- Code:
- Exact Method Body:
return StringParse.b64MimeStrToObj(loadFileToString(fileName));
-
readObjectFromTextFileNOCNFE
public static <T> T readObjectFromTextFileNOCNFE (java.lang.String fileName, java.lang.Class<T> c) throws java.io.IOException
- Code:
- Exact Method Body:
try { return readObjectFromTextFile(fileName, c); } catch (ClassNotFoundException cnfe) { return null; }
-
readObjectFromTextFile
public static <T> T readObjectFromTextFile(java.lang.String fileName, java.lang.Class<T> c) throws java.io.IOException, java.lang.ClassNotFoundException
This will read a java serialized, and MIME-Converted, MIME-Safejava.lang.Stringfrom a text file and return theObjectthat it represented
Serializable Collections:
When multiplejava.lang.Object'sneed to be stored, it is very-often more advisable to first save those objects to one of Java's manyjava.util.Collection'sorjava.util.List'sclasses. SavingSerializable-Objects to aCollectionorList, 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 theSerializableinterface, so writing / serializing an entireVector(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 methodwriteObjectToFile(...)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 aB64 MIME-Encode Stringand written.
Then thisStringis 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'intoMIME-Encodedtext.
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 theObject(unless thatObjectis 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 Serializedjava.lang.Object.c- This is the type of theObjectexpecting to be read from disk. A value for this parameter can always be obtained by referencing thestaticfield'.class', which is attached to everyObjectin java.The parameterClass lt;T> cspecifies the expected runtime type of theObjectread from the file. This enables the method to return a correctly typed reference of typeT. 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 ofClass<T>is to just cite the field'.class'which which is a static member present within everyclass-Type in Java. For instance, if a user were intending to read aTreeSetfrom disk, all he or she needs to do is passTreeSet.classto this parameter.Run-Time Generic Erasure: Due to Java's type-erasure model, Generic Type-Parameters like<String>are not preserved at runtime. As a result, this method cannot determine the specific type parameter of generic types — only their raw class. Despite this, for most practical cases - especially single non-generic objects, this method should work exactly as expected.
However, if reading, say - an instance ofVector<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.
IfVector.classis passed to parameter'c', this method will be returning the Raw-TypeVector, and your code will therefore need to cast the Returned-Value toVector<String>to avoid the Java-Compiler's "Raw-Type Warnings." Again, this cast is necessary becauseVector.classalone does not actually "carry" or "contain" the Generic-Type information -<String>
However, and lastly, this cast will produce an "Unchecked Cast Warning" - and that means adding the very-commonly-used@SuppressWarnings("unchecked")Annotation. Notice in the example below how theVector.classparameter, itself, is insufficient for specifying the return of aVector<String>. However, using a cast and a SuppressWarnings annotation resolves the issue cleanly.
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);
Note Regarding Data: If the file being read did not actually have aVectorcontaining onlyString-instances. This may result in "Heap Pollution" — which is a state where type safety is violated at runtime due to unchecked Generic-Casts.- Returns:
- The
Objectthat 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 theCLASSPATH.- See Also:
StringParse.b64MimeStrToObj(String),loadFileToString(String)- 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 simpleObjectInputStream- usually if multipleObject'shave been written to a single file. It was better practice to putObject'sin ajava.util.Vector, and write onejava.util.Vectorduring 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 serializedObject'shave been stored.ZIP- If this is set toTRUE, 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 simpleObjectOutputStream- usually if multipleObject'sneed to be written to a single file. It was better practice to putObject'sin ajava.util.Vector, and write onejava.util.Vectorduring serialization.- Parameters:
fName- This is the File-Name of the Data-File where the serializedObject'swill be stored.ZIP- If this is set toTRUE, 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 endingFile.separator, but does not appear to name a directory that exists, this method will throw aFileNotFoundException.
This can be avoided, however, by passingTRUEto parameter'createDirsIfNotExist'. If'outFileOrDirName'specifies a directory (by virtue of the fact that it ends with theFile.separator String) - and'createDirsIfNotExist'isTRUE, then this method will first create any and all sub-directories needed using the standard Java'sFile.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 standardUNIXorMS-DOScommands'cp'and'copy'(respectively) - differing only in this method's ability to have directories created usingFile.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 toTRUEand the aforementioned situation occurs where the complete-directory tree does not exist, then this method will first attempt to create the directories usingjava.io.File.mkdirs().- Throws:
java.lang.SecurityException- If boolean parameter'createDirsIfNotExist'isTRUEand 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 toFALSE.SameSourceAndTargetException- This exception will be thrown if theJava Virtual Machineascertains that the source and target locations point to the same physical disk locations. The classes utilized for this operation are from packagejava.nio.file.*;java.nio.file.InvalidPathException- If the Java Virtual Machine is unable to instantiate an instance ofjava.nio.files.Pathfor either the'inFileName'parameter or the'outFileOrDirName', then this exception will be thrown.java.nio.file.NoSuchFileException- If, after instantiating an instance ofPathfor either thesourceor thetargetlocations, the Java Virtual Machine is unable to build an instance ofPathusing the methodPath.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(); }
-
deleteFiles
public static void deleteFiles(java.lang.String... fileNames)
Convenience Method
Invokes:java.io.File.delete()- Code:
- Exact Method Body:
for (String fileName : fileNames) (new File(fileName)).delete();
-
moveFile
public static void moveFile(java.lang.String inFileName, java.lang.String outFileName, boolean createDirsIfNotExist) throws java.io.IOException
- 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-rfor the commandrm, or the old Microsoft DOS Command'deltree'for deleting directories. It simply reuses the classFileTransfer
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 toShell.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 classShellwould 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 ofTRUE, the equivalent of the UNIX commandmkdir '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'sjava.lang.Appendableinterface which allows for a wide range of options when logging intermediate messages.Class or Interface Instance Use & Purpose 'System.out'Sends text to the standard-out terminal Torello.Java.StorageWriterSends text to System.out, and saves it, internally.FileWriter, PrintWriter, StringWriterGeneral purpose java text-output classes FileOutputStream, PrintStreamMore general-purpose java text-output classes
Checked IOException:
TheAppendableinterface requires that the Checked-ExceptionIOExceptionbe caught when using itsappend(...)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 theStringprovided to parameterdirectoryNamedoes not name a valid directory on the File-System.java.io.IOException- May be thrown by the File-System Methods which underly this method.- 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 passTRUEto the parameter'isCSV'. If this file contains integers that have commas between digits in groups of three (like'30,000') please passTRUEto 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 suchint'son a particular line. The file may also have any number of suchint-containing lines. Blank lines found within the input file will are simply ignored.
If parameter'isCSV'is passedFALSE, 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 passedTRUE, then eachintmust be separated by a comma character.Number-Format: The numbers in this Text-File must be parse-able by Java classjava.lang.Integervia its methodInteger.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 toTRUE, 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 passTRUEto this parameter. IfFALSEis 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 toTRUE- 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'sclass java.lang.Integeris used to perform the parse, both the'radix', and the data found in the Text-File must conform to the Java methodInteger.parseInt(String s, int radix).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.IntStreamconsisting of the integers that were found within the Text-File provided by'fileName'.An instance ofIntStreamis easily converted to anint[]array using the methodIntStream.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 passTRUEto the parameter'isCSV'. If this file contains integers that have commas between digits in groups of three (like'30,000') pleas passTRUEto 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 suchlong'son a particular line. The file may also have any number of suchlong-containing lines. Blank lines found within the input file will are simply ignored.
If parameter'isCSV'is passedFALSE, 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 passedTRUE, then eachlongmust be separated by a comma character.Number-Format: The numbers in this Text-File must be parse-able by Java classclass java.lang.Longusing the methodLong.parseLong(String s, int radix)- Parameters:
fileName- This should contain the File-Name which itself contains a list of'long'integers. Theselongintegers may be separated by either a comma (',') or a space (' ').hasCommasInLongs- It is allowed that the file named by'fileName'containlong-integers which use the commonly found notation of having a comma between groups of three digits within alonginteger. For instance the number'98765', to a reader, is often represented as'98,765'. When this parameter is set toTRUE, 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 passTRUEto this parameter. IfFALSEis 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 toTRUE- where thelongintegers have commas, and thelongintegers 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'sclass Longis used to perform the parse, both the'radix', and the data found in the Text-File must conform to the Java methodLong.parseLong(String s, int radix).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.LongStreamconsisting of thelong-integers that were found within the Text-File provided by'fileName'.An instance ofLongStreamis easily converted to along[]array using the methodLongStream.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 passTRUEto the parameter'isCSV'. If this file containsdouble'sthat have commas between digits in groups of three (like'30,000,000,00') pleas passTRUEto 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 suchlong'son a particular line. The file may also have any number of suchlong-containing lines. Blank lines found within the input file will are simply ignored.
If parameter'isCSV'is passedFALSE, 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 passedTRUE, then eachlongmust be separated by a comma character.Number-Format: The numbers in this Text-File must be parse-able by Java classclass java.lang.Doubleusing the methodDouble.parseDouble(String s)- Parameters:
fileName- This should contain the File-Name which itself contains a list of'double'values. Thesedouble'smay be separated by either a comma (',') or a space (' ').hasCommasInDoubles- It is allowed that the file named by'fileName'containdouble-values which use the commonly found notation of having a comma between groups of three digits within adoublevalue. For instance the number'98765.01', to a reader, can be represented as'98,765.01'. When this parameter is set toTRUE, 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 passTRUEto this parameter. IfFALSEis 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 toTRUE- where thedoublevalues have commas, and thedoublevalues 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.DoubleStreamconsisting of thedouble-values that were found within the Text-File provided by'fileName'.An instance ofDoubleStreamis easily converted to adouble[]array using the methodDoubleStream.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 throwIOException, 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 throwIOException, 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) throws java.io.FileNotFoundException, java.io.IOException
- Code:
- Exact Method Body:
return readBinary(fileName, 0, -1);
-
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 Javabyte[]array.
Unlike Java'sFileOutputStream.write(...)method, theread(...)Java provides in that same exact class is more difficult to use. This method is much longer than its correspondingwriteBinary(byte[], String)method.- Parameters:
fileName- The name of the file (on the File-System) to read.offset- The number ofbyte'sto skip before appending abyteinto the outputbyte[]array. If the value provided to parameer'offset'is longer than the size of the file itself, then a zero-lengthbyte[]array will be returned.The meaning of the value in parameter'offset'is very different from the meaning of a parameter by that exact same name, except in methodread(...)of classFileInputStream. HERE the offset is the number of bytes to skip inside of file'fileName', before saving the values that are read froom disk. In theFileInputStream, offset is used as an array pointer.len- Once the internal-loop has begun copying bytes from the Data-File into the returnedbyte[]array,byte'swill continue to be copied into this array until precisely'len'bytes have been copied.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- Classjava.io.FileInputStreamwill throw aFileNotFoundExceptionif 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 itscheckReadmethod denies read access to the file.java.io.IOException- TheFileInputStreaminstance, and thejava.io.Fileinstance are both capable of throwingIOException.java.lang.IllegalArgumentException-- The value provided to
'offset'is negative - The value provided to parameter
'len'is zero.
- The value provided to
FileSizeException- This exception throws if any of the following are detected:- The returned
byte[]array cannot have a size larger thanInteger.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 + lenis 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.
- The returned
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 anEOFearlier than expected (for unforseen reasons), thenEOFExceptionwould 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 ajava.lang.Classfrom a class-file.
It is not neccessarily always knownst to the programmer what the Full-Package Class-Name of theclassthat'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 onlyStringpassed to this Var-ArgsString-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 (using the standard JDK) to read a class file, and then ask that class-file either:- What the name of the
Classin the Class-File is? - What the name of the
Packagebeing used in that Class-File is?
So, for now, a Var-ArgsString-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.- What the name of the
- Returns:
- An instance of
java.lang.Classthat was contained by the Class-File. - Throws:
java.io.IOException- Java may throw several exceptions while attempting to load the'.class'file into abyte[]array. Such exceptions may includeIOException,SecurityException,FileNotFoundExceptionetc...java.lang.TypeNotPresentException- If none of the names listed in Var-ArgsString[]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', thisRuntimeExceptionis 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 );
-
-