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 quite a few of the standardjava.io.*
file operations. The operations that Java provides are mostly "pretty useful" - however, if one is not overtly concerned with the optimization of disk reads or writes, what this package provides is many orders of code simplification. Many of the append, read and write operations instantiate ajava.io.File
and/orjava.io.OutputStream
, and open and close thoseObject's / classes
in the same method/function body.
FileRW.appendToFile(...)
for instance, opens the File-Pointer, writes theString,
and then closes it immediately. However, the 4 or 5 lines of code that each of these methods/functions eliminate make text-processing code and language-translation code a lot easier to read. With text-processing and language-translation, one might find oneself writing file data once a day, and never for very long. A few milliseconds is expended by opening and closing these file-pointers, but the code that I have written is world's easier to read.
FileRW.writeObjectToFile(...)
for instance, allows a user who is writing aVector<String>
(which for all intents-and-purposes is Java's way of saying "data-file" via "object-serialization"), to write theVector
to a file in a single line of code. This utilizes Java's object-serialization code, compression code, and file IO code in a single method, efficiently - saving a programmer potential for headache and bugs.
Hi-Lited Source-Code:- View Here: Torello/Java/FileRW.java
- Open New Browser-Tab: Torello/Java/FileRW.java
Stateless Class:This class neither contains any program-state, nor can it be instantiated. The@StaticFunctional
Annotation may also be called 'The Spaghetti Report'.Static-Functional
classes are, essentially, C-Styled Files, without any constructors or non-static member fields. It is a concept very similar to the Java-Bean's@Stateless
Annotation.
- 1 Constructor(s), 1 declared private, zero-argument constructor
- 48 Method(s), 48 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 boolean
TRUNCATE_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 String
loadFileToString(String fName)
static String[]
loadFileToStringArray(String fName, boolean includeNewLine)
static StringBuffer
loadFileToStringBuffer(String fName)
static StringBuilder
loadFileToStringBuilder(String fName)
static Vector<String>
loadFileToVector(String fName, boolean includeNewLine)
Write Text Files Modifier and Type Method static void
appendToFile(CharSequence s, String fName)
static void
writeFile(CharSequence s, String fName)
static void
writeFile(Iterable<String> i, String fName)
static void
writeFile(Iterator<String> i, String fName)
static void
writeFile(Stream<String> stringStream, String fName)
static void
writeFile_NO_NEWLINE(Iterable<String> i, String fName)
static void
writeFile_NO_NEWLINE(Iterator<String> i, String fName)
static void
writeFile_NO_NEWLINE(Stream<String> stringStream, String fName)
Read Serialized-Object(s) Modifier and Type Method static ObjectInputStream
getOIS(String fName, boolean ZIP)
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)
static Object
readObjectFromFile(String fName, boolean ZIP)
static <T> T
readObjectFromFile(String fName, Class<T> c, boolean ZIP)
static Object
readObjectFromFileNOCNFE(String fName, boolean ZIP)
static <T> T
readObjectFromFileNOCNFE(String fName, Class<T> c, boolean ZIP)
static Object
readObjectFromTextFile(String fileName)
static <T> T
readObjectFromTextFile(String fileName, Class<T> c)
static <T> T
readObjectFromTextFileNOCNFE(String fileName, Class<T> c)
Write Serialized-Object(s) Modifier and Type Method static ObjectOutputStream
getOOS(String fName, boolean ZIP)
static void
writeAllObjectsToFile(Iterable<?> i, String fName, boolean ZIP)
static void
writeAllObjectsToFile(Iterator<?> i, String fName, boolean ZIP)
static boolean
writeAllObjectsToFileNOCNFE(Iterable<?> i, String fName, boolean ZIP)
static boolean
writeAllObjectsToFileNOCNFE(Iterator<?> i, String fName, boolean ZIP)
static void
writeObjectToFile(Object o, String fName, boolean ZIP)
static boolean
writeObjectToFileNOCNFE(Object o, String fName, boolean ZIP)
static void
writeObjectToTextFile(Object o, String fileName)
Move, Copy & Delete Modifier and Type Method static void
copyFile(String inFileName, String outFileOrDirName, boolean createDirsIfNotExist)
static void
deleteFiles(String... fileNames)
static int
delTree(String directoryName, boolean reCreateDirectoryOnExit, Appendable log)
static void
moveFile(String inFileName, String outFileName, boolean createDirsIfNotExist)
Read Text-Numbers Modifier and Type Method static DoubleStream
readDoublesFromFile(String fileName, boolean hasCommasInDoubles, boolean isCSV)
static IntStream
readIntsFromFile(String fileName, boolean hasCommasInInts, boolean isCSV, int radix)
static LongStream
readLongsFromFile(String fileName, boolean hasCommasInLongs, boolean isCSV, int radix)
Read & Write byte[]
arrays to Binary-FilesModifier and Type Method static byte[]
readBinary(String fileName)
static byte[]
readBinary(String fileName, int offset, int len)
static Class<?>
readClass(String classFileName, String... possibleClassNames)
static void
writeBinary(byte[] bArr, int offset, int len, String fileName)
static void
writeBinary(byte[] bArr, String fileName)
-
-
-
Field Detail
-
TRUNCATE_EOF_CHARS
public static boolean TRUNCATE_EOF_CHARS
This is used by methodloadFileToString(String)
. By default this flag is set to TRUE, and when it is, any trailingEOF chars, ASCII-0
found in a file that is to be interpreted as a text-file, will be truncated from theString
returned 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.String
to a file on the file-system named'fName'
.
NOTE: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java'IOException'
will occur.- Parameters:
s
- Ajava.lang.String
which is appended, in entirety, to the file ('fName')fName
- The name of the file to which the contents of thejava.lang.String
are appended. If This file doesn't already exist, it is created here.- Throws:
java.io.IOException
- If any I/O errors have occurred with the file-system / disk.- Code:
- Exact Method Body:
File outF = new File(fName); outF.createNewFile(); // This writer is 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! try (FileWriter fw = new FileWriter(outF)) { fw.write(s.toString()); }
-
writeFile
public static void writeFile(java.lang.Iterable<java.lang.String> i, java.lang.String fName) throws java.io.IOException
- Code:
- Exact Method Body:
writeFile(i.iterator(), fName);
-
writeFile
public static void writeFile (java.util.stream.Stream<java.lang.String> stringStream, java.lang.String fName) throws java.io.IOException
- Code:
- Exact Method Body:
writeFile(stringStream.iterator(), fName);
-
writeFile
public static void writeFile(java.util.Iterator<java.lang.String> i, java.lang.String fName) throws java.io.IOException
This takes anIterator<String>
, and a filename, and writes eachjava.lang.String
in theIterator
to the file named by parameter'fName'
NOTE: A newline('\n')
is appended to the end of eachjava.lang.String
before writing it to the file.
ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java'IOException'
will occur.- Parameters:
i
- This is any 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.String
are appended. If This file doesn't already exist, it is created here.- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
File 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 (i.hasNext()) fw.write(i.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
- Code:
- Exact Method Body:
writeFile_NO_NEWLINE(i.iterator(), fName);
-
writeFile_NO_NEWLINE
public static void writeFile_NO_NEWLINE (java.util.stream.Stream<java.lang.String> stringStream, java.lang.String fName) throws java.io.IOException
- Code:
- Exact Method Body:
writeFile_NO_NEWLINE(stringStream.iterator(), fName);
-
writeFile_NO_NEWLINE
public static void writeFile_NO_NEWLINE (java.util.Iterator<java.lang.String> i, java.lang.String fName) throws java.io.IOException
This takes anIterator
of String, and a filename and writes eachjava.lang.String
in theIterator
to the file named by parameter'fName'
NOTE: in this function a newline('\n')
character is not appended to the end of eachjava.lang.String
of the inputIterator
.
ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java'IOException'
will occur.- Parameters:
i
- This is any java'Iterable'
object that can iterate'String'
. Each of these will be written, in succession, to the file named by'fName'
fName
- The name of the file to which the contents of thejava.lang.String
are appended. If This file doesn't already exist, it is created here.- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
File 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 (i.hasNext()) fw.write(i.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.CharSequence
to the file on the file-system named'fName'
NOTE: Though the file does not need to exist already in order for this file to be written the directory hierarchy needs to exist, or a java'IOException'
will occur.- Parameters:
s
- 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.String
are appended. If This file doesn't already exist, it is created here.- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
File f = new File(fName); if (! f.exists()) f.createNewFile(); Files.write(Paths.get(fName), s.toString().getBytes(), StandardOpenOption.APPEND);
-
loadFileToStringBuffer
public static java.lang.StringBuffer loadFileToStringBuffer (java.lang.String fName) throws java.io.IOException
- Code:
- Exact Method Body:
return (new StringBuffer()).append(loadFileToString(fName));
-
loadFileToStringBuilder
public static java.lang.StringBuilder loadFileToStringBuilder (java.lang.String fName) throws java.io.IOException
- Code:
- Exact Method Body:
return (new StringBuilder()).append(loadFileToString(fName));
-
loadFileToString
public static java.lang.String loadFileToString(java.lang.String fName) throws java.io.IOException
This will load the entire contents of a text-file on disk to a singlejava.lang.String
TRUNCATES TRAILING ZEROES: Some of the ugliest code to see is that which finds'EOF'
characters liberally inserted into a simple text-file. When reading a file (which, regardless of whether it actually is a text-file), this method will remove any trailingASCII-0
characters (literally,char c == 0
) from the files that are read. Finding'.html'
or'.java'
files in which some editor (for whatever reason) has insertedEOF-like
characters to the end of the text can make programming a headache.
Suffice it to say, theString
that is returned from this method will contain the last non-zero character (including CRLF,'\n'
or'\r'
character that was read from the file. Operating-systems do not need to have a trailing zero (legacy'End-of-File'
marker) at the end of a text-file in order to interpret that file. JavaString's
certainly have no use for them, and when worry about things likeequality-tests
inside Java loops, eliminating theEOF
character altogether is actually best.
FINALLY: This class has astatic boolean
flat can shunt this behavior, and allString's
returned will include as many trailing zero characters at the end of theString
returned by this method as the JavaFileReader
class finds. SeeTRUNCATE_EOF_CHARS
.- Parameters:
fName
- the file-name of a valid text-file in the file-system- Returns:
- The entire contents of the file as a
String
. - Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
// 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
- 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 ajava.lang.StringBuilder
instance.- Parameters:
fName
- A file-name of a valid text-file in the file-system.includeNewLine
- if this is TRUE, a'\n'
(newline/CRLF) is appended to the end of eachjava.lang.String
read from this file. If not, the original newline characters which occur in the file, will be eliminated.
MINOR NOTE: This method will make one (potentially minor) mistake. If the final character in the input-file is, itself, a new-line (if the file ends with a'CRLF' / 'CR'
), then this method should return 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 lastString
in 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.String
contained by ajava.util.stream.Stream<String>
. Converting JavaStream's
to other data container types is as follows:Conversion-Target Stream-Method Invocation String[]
Stream.toArray(String[]::new);
List<String>
Stream.collect(Collectors.toList());
Vector<String>
Stream.collect(Collectors.toCollection(Vector::new));
TreeSet<String>
Stream.collect(Collectors.toCollection(TreeSet::new));
Iterator<String>
Stream.iterator();
- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
// These readers's are 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. try ( FileReader fr = new FileReader(fName); BufferedReader br = new BufferedReader(fr); ) { Stream.Builder<String> b = Stream.builder(); String s = ""; if (includeNewLine) while ((s = br.readLine()) != null) b.add(s + "\n"); else while ((s = br.readLine()) != null) b.add(s); return b.build(); }
-
loadFileToVector
public static java.util.Vector<java.lang.String> loadFileToVector (java.lang.String fName, boolean includeNewLine) throws java.io.IOException
- 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.String
in the output / returnedCollection
is a different "line of text" from the input-file. This is identical to using the method frompublic String[] java.lang.String 'split("\n")'
- and then saving each of theString's
from theString-array
into an element of the returnedCollection<String>
This method uses Java's variable-type parameter syntax to allow the programmer to decide what type ofCollection<String>
to obtain from this method. The standard JavaCollection's
include:TreeSet, Vector, ArrayList, HashSet
, among others. Provide anew Collection<String>
by simply calling a constructor to one of these classes like:new Collection<String>()
.
MINOR NOTE: This method will make one (potentially minor) mistake. If the final character in the input-file is, itself, a new-line (if the file ends with a'CRLF' / 'CR'
), then this method should return aCollection<String>
that is identical to the original file. However, if the final character in the file is not a new-line'\n'
, then theCollection<String>
that is returned will have an extra new-line appended to the lastString
in theCollection
, and 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 is TRUE, a'\n'
(newline/CRLF) is appended to the end of eachjava.lang.String
read from this file. If not, the original newline characters which occur in the file, will be eliminated.- Returns:
- An identical reference to the reference passed to parameter
'collectionChoice'
- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
// These readers's are 'java.lang.AutoCloseable'. // // NOTE: The IOException will still be thrown out of this method if it occurs. It is not // caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. try ( FileReader fr = new FileReader(fName); BufferedReader br = new BufferedReader(fr); ) { String s = ""; if (includeNewLine) while ((s = br.readLine()) != null) collectionChoice.add(s + "\n"); else while ((s = br.readLine()) != null) collectionChoice.add(s); } return collectionChoice;
-
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.Object
to a file for storage, and future reference.
ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a javaIOException
will occur.- Parameters:
o
- AnObject
to be written to a file as a "Serializable"java.lang.Object
fName
- The name of the output fileZIP
- a boolean that, when TRUE, will cause the object's data to be compressed before being written to the output file.- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.java.lang.ClassNotFoundException
- This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath.- Code:
- Exact Method Body:
// These stream's are 'java.lang.AutoCloseable'. // // NOTE: The IOException and ClassNotFoundException will still be thrown out of this // method if they occur. They are not caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. if (ZIP) try ( FileOutputStream fos = new FileOutputStream(fName); GZIPOutputStream gzip = new GZIPOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(gzip); ) { oos.writeObject(o); } else try ( FileOutputStream fos = new FileOutputStream(fName); ObjectOutputStream oos = new ObjectOutputStream(fos); ) { oos.writeObject(o); }
-
writeAllObjectsToFile
public static void writeAllObjectsToFile(java.lang.Iterable<?> i, java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
- Code:
- Exact Method Body:
writeAllObjectsToFile(i.iterator(), fName, ZIP);
-
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.iterator(), fName, ZIP); return true; } catch (ClassNotFoundException cnfe) { return false; }
-
writeAllObjectsToFileNOCNFE
public static boolean writeAllObjectsToFileNOCNFE(java.util.Iterator<?> i, java.lang.String fName, boolean ZIP) throws java.io.IOException
- Code:
- Exact Method Body:
try { writeAllObjectsToFile(i, fName, ZIP); return true; } catch (ClassNotFoundException cnfe) { return false; }
-
writeAllObjectsToFile
public static void writeAllObjectsToFile(java.util.Iterator<?> i, java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
Writes a series ofjava.lang.Object
to a file for storage, and future reference.
ALSO: Though the file does not need to exist already in order for this file to be written (in fact, if it does exist - it will be 'over-written') the directory hierarchy needs to exist, or a java'IOException'
will occur.
NOTE: When multiplejava.lang.Object's
need to be stored, it is sometimes advisable to save them to one of Java's many standardjava.util.Collection
classes, or possibly to ajava.util.List
class, first. Saving multipleObjects's
to ajava.util.Collection
, and then writing that singleCollection Object
to disk can often make code look cleaner.
Keep in mind that all of Java's'java.util.*'
generic data-structures implement theinterface java.io.Serializable
, so writing / serializing an entireVector<Object>
is extremely simple, as long as all of theObject's
contained by theVector
also implementSerializable
(or are 'de-facto' Serializable by the JVM).- Parameters:
i
- A series,Collection
, orList
ofObject's
to be written to a file in Serializable format.fName
- The name of the output fileZIP
- aboolean
that, when TRUE, will cause theObject'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 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. if (ZIP) try ( FileOutputStream fos = new FileOutputStream(fName); GZIPOutputStream gzip = new GZIPOutputStream(fos); ObjectOutputStream oos = new ObjectOutputStream(gzip); ) { while (i.hasNext()) oos.writeObject(i.next()); } else try ( FileOutputStream fos = new FileOutputStream(fName); ObjectOutputStream oos = new ObjectOutputStream(fos); ) { while (i.hasNext()) oos.writeObject(i.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 anObject
from 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;
NOTE: When multiplejava.lang.Object's
need to be stored, it is sometimes advisable to save them to one of Java's many standardjava.util.Collection
classes, or possibly to ajava.util.List
class, first. Saving multipleObjects's
to ajava.util.Collection
, and then writing that singleCollection Object
to disk can often make code look cleaner.
Keep in mind that all of Java's'java.util.*'
generic data-structures implement theinterface java.io.Serializable
, so writing / serializing an entireVector<Object>
is extremely simple, as long as all of theObject's
contained by theVector
also implementSerializable
(or are 'de-facto' Serializable by the JVM).- Parameters:
fName
- The name of a data-file that contains a serializedjava.lang.Object
ZIP
- if this is TRUE, it is assumed that the data-file contains a zip-compressedObject
- Returns:
- The
Object
that was written to the data-file. - Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.java.lang.ClassNotFoundException
- This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in 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 anObject
from a data-file which must contain a serializedjava.lang.Object
.
NOTE: When multiplejava.lang.Object's
need to be stored, it is sometimes advisable to save them to one of Java's many standardjava.util.Collection
classes, or possibly to ajava.util.List
class, first. Saving multipleObjects's
to ajava.util.Collection
, and then writing that singleCollection Object
to disk can often make code look cleaner.
Keep in mind that all of Java's'java.util.*'
generic data-structures implement theinterface java.io.Serializable
, so writing / serializing an entireVector<Object>
is extremely simple, as long as all of theObject's
contained by theVector
also implementSerializable
(or are 'de-facto' Serializable by the JVM).- 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.Object
c
- This is the type of theObject
expecting to be read from disk. A value for this parameter can always be obtained by referencing thestatic
field'.class'
which is attached to every object in java.
ALSO: The 'type parameter' (Class<T> c
) is used to indicate the expected type of thejava.lang.Object
that is read, and ultimately returned. This method employs Java's variable-type method syntax. Variable-type parameter<T>
may be anyclass
at all (as long as were Serializable).
Generally, the easiest way to obtain an instance ofClass<T>
is to just cite the field'.class'
that everyjava.lang.Object
contains. For instance, if a user was intending to read aTreeSet
from disk, then specifying that an instance ofClass<TreeSet>
is desired would be as simple as passingTreeSet.class
to this method's'c'
parameter.
GENERIC-ERASURE: Generally because of the concept known as "Generic Erasure" - Variable-Type Parametrized Methods in Java do not function as well as they could. When reading a non-genericObject
from a data-file, the read-operation implemented by this method should work just fine - as long as Java was able to'serialize'
theObject
(which it is able to do most of the time regardless of whether the user has implemented theinterface java.io.Serializable
- by using 'de-facto', automated serialization).
However, if writing, say, an instance ofVector<String>
, the user needs to keep in mind that the stated return-type of this method, when passed the referenceVector.class
, will be of araw-type
'Vector'
, not of typeVector<String>
. Therefore a'cast'
is in order, however, this'cast'
will generate a warning ofunchecked cast
- unless the@SuppressWarnings("unchecked") Annotation
is carefully specified. Notice in the example how theVector.class
parameter, itself, is insufficient to return a aVector<String>
. Here, use acast
, and suppress the compiler warning messages:
Example:
// Generate a Data-Set, and save it to a String-Vector Vector<String> myData = some_data_operation(); // Save this 'Object' (Vector) to disk, in a file named "StringVector.dat" // NOTE: Always passing "true" to the 'ZIP' parameter is usually easiest. // ALSO: We are writing *a single object* (a Vector), even though this Vector is a // collection, it counts as just a single-object in this write. FileRW.writeObjectToFile(myData, "StringVector.dat", true); // To retrieve this Vector - as a Vector<String> reference - use the following // specifier and cast. The "SuppressWarnings" is needed because this is a "generic" // type (Vector<E>) which has a generic-type parameter which IS NOT included information // inside the class 'Vector.class' @SuppressWarnings("unchecked") Vector<String> myData2 = (Vector<String>) FileRW.readObjectFromFile("StringVector.dat", Vector.class, true); // The data-retrieval - AND COMPILER TYPE-CHECKING - should then work all right. // NOTE: This 'extra-cast' is *ONLY* important when serializing a GENERIC-class that // uses the 'ClassName<E>' generic-parameter notation (greater-than and less-than // symbols)... // For serializing 'regular' classes: String, Integer, etc... no such 'extra' cast // is needed - simply use: String.class, Integer.class, etc... // ********************************************************************* // IMPORTANT NOTE: The Same Rational Applies for the 'fromTextFile(...)' // object serializers: // ********************************************************************* FileRW.writeObjectToTextFile(myData, "StringVector.txt"); @SuppressWarnings("unchecked") Vector<String> myData3 = (Vector<String>) FileRW.readObjectFromTextFile("StringVector.txt", Vector.class);
DATA-NOTE: If the file being read did not actually have aVector
which contained only instances ofString
, this could lead non-deterministic results (sometimes called "heap-pollution").ZIP
- if this is TRUE, it is assumed that the data-file contains a zip-compressedObject
- Returns:
- The
Object
that was read from the data-file. - Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.java.lang.ClassNotFoundException
- This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in 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
- 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
- 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's
found 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's
are stored in the Serialized Object File, specified by'fName'
.U
- Merely for convenience, this method returns theCollection
instance that is passed (by parameter'Collection'
) as a result of this function. Therefore, the Type Parameter'U'
identifies the Return Type of this method.- Parameters:
objType
- This is the type /'Class<C>'
of theObject's
that the user is expecting to read from disk. A value for this parameter can always be obtained by referencing thestatic
field'.class'
which is attached to everyObject / Class
in java. For instance, to read a data-file containing a series ofjava.lang.Integer
instances, useInteger.class
as the value to pass to this parameter. See below example:
Example:
// the java.util.TreeSet class is used to store a list of integers. TreeSet<Integer> myData = some_data_calculation(); // Write this data-set to disk in a file-named "myDataFile.data" FileRW.writeAllObjectsToFile(myData, "etc/myDataFile.dat", true); // To read this file back from disk: // NOTE: The "SuppressWarnings" Annotation is NOT NEEDED HERE, because all // available type information has been passed to the method. TreeSet<Integer> myData = FileRW.readAllObjects (Integer.class, new TreeSet<>(), "etc/myDataFile.dat", true);
collection
- This should be the 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's
ZIP
- if this is TRUE, it is assumed that the data-file contains zip-compressed objects- Returns:
- A reference to the
Collection
that was passed to this method. - Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.java.lang.ClassNotFoundException
- Code:
- Exact Method Body:
// Temporary Variable, used in both versions of this method Object o; // These stream's are 'java.lang.AutoCloseable'. // // NOTE: The IOException and ClassNotFoundException will still be thrown out of this // method if they occur. They are not caught! // // ALSO: In try-with-resources blocks, if there is a problem/exception, these // classes are all (automatically) closed/flushed, in reverse order. if (ZIP) try ( FileInputStream fis = new FileInputStream(fName); GZIPInputStream gis = new GZIPInputStream(fis); ObjectInputStream ois = new ObjectInputStream(gis); ) { while ((o = ois.readObject()) != null) if (objType.isInstance(o)) collection.add(objType.cast(o)); else throw new ClassNotFoundException( "At least one of the objects in the serialized object file " + "[" + fName + "], " + "was not an instance of [" + objType.getName() + "], " + "but rather [" + o.getClass().getName() + "]" ); } catch (EOFException eofe) { } else try ( FileInputStream fis = new FileInputStream(fName); ObjectInputStream ois = new ObjectInputStream(fis); ) { while ((o = ois.readObject()) != null) if (objType.isInstance(o)) collection.add(objType.cast(o)); else throw new ClassNotFoundException( "At least one of the objects in the serialized object file " + "[" + fName + "], " + "was not an instance of [" + objType.getName() + "], " + "but rather [" + o.getClass().getName() + "]" ); } catch (EOFException eofe) { } return collection;
-
readAllObjectsToStream
public static java.util.stream.Stream<java.lang.Object> readAllObjectsToStream (java.lang.String fName, boolean ZIP) throws java.io.IOException, java.lang.ClassNotFoundException
- Code:
- Exact Method Body:
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 JavaStream
that 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's
objType
- This is the type of theObject's
expecting to be read from disk. A value for this parameter can always be obtained by referencing the static field'.class'
which is attached to everyObject
in java. For instance, to read a data-file containing a series ofDate
instances, useDate.class
as the value to pass to this parameter.ZIP
- if this is TRUE, it is assumed that the data-file contains zip-compressedObject's
- Returns:
- A
Stream<T>
of allObject's
found in the data-file. Converting JavaStream's
to other data container types is as follows:Conversion-Target Stream-Method Invocation T[]
Stream.toArray(T[]::new); /* Use Actual Class of T, generic array creation is not allowed in Java. */
List<T>
Stream.collect(Collectors.toList());
Vector<T>
Stream.collect(Collectors.toCollection(Vector::new));
TreeSet<T>
Stream.collect(Collectors.toCollection(TreeSet::new));
Iterator<T>
Stream.iterator();
- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.java.lang.ClassNotFoundException
- This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in the classpath.- Code:
- Exact Method Body:
Stream.Builder<T> b = Stream.builder(); Object o = null; FileInputStream fis = new FileInputStream(fName); ObjectInputStream ois = ZIP ? new ObjectInputStream(new GZIPInputStream(fis)) : new ObjectInputStream(fis); try { while ((o = ois.readObject()) != null) if (objType.isInstance(o)) b.accept(objType.cast(o)); else throw new ClassNotFoundException( "At least one of the objects in the serialized object file [" + fName + "], " + "was not an instance of [" + objType.getName() + "], " + "but rather [" + o.getClass().getName() + "]" ); } catch (EOFException eofe) { } finally { fis.close(); } return b.build();
-
writeObjectToTextFile
public static void writeObjectToTextFile(java.lang.Object o, java.lang.String fileName) throws java.io.IOException
Uses Java'sObject
serialization mechanism to serialize ajava.lang.Object
, and then uses theBase64 String-MIME Encoding
system, also provided by java, to convert theObject
into a text-safejava.lang.String
that may be viewed, e-mailed, written to a web-page, etc.
NOTE: When multiplejava.lang.Object's
need to be stored, it is sometimes advisable to save them to one of Java's many standardjava.util.Collection
classes, or possibly to ajava.util.List
class, first. Saving multipleObjects's
to ajava.util.Collection
, and then writing that singleCollection Object
to disk can often make code look cleaner.
Keep in mind that all of Java's'java.util.*'
generic data-structures implement theinterface java.io.Serializable
, so writing / serializing an entireVector<Object>
is extremely simple, as long as all of theObject's
contained by theVector
also implementSerializable
(or are 'de-facto' Serializable by the JVM).
This loads the contents of an international website from Europe, and parses the output into aVector<HTMLNode>
. This output is printed to disk, and then it is saved as aB64 MIME-Encode String
and also written to disk. Then thisString
is re-loaded and written out as HTML a second time to verify and ensure that no information was lost in the conversion of the Java'POJO'
intoMIME-Encoded
text.
Example:
// Visit and parse a "Spanish Newspaper" (from Iberia, Spain). Save to HTML Vector. URL url = new URL("https://elpais.com/"); Vector<HTMLNode> html = HTMLPage.getPageTokens(url, false); // Write the HTML out as a MIME-Encoded Java Serialized Object (of the Vector<HTMLNode> // The file itself will resemble 1990's e-mail MIME Messages. FileRW.writeObjectToTextFile(html, "myFile.txt"); // Write the HTML out as a '.html' file FileRW.writeFile(Util.pageToString(html), "myFile1.html"); // Reload the HTML Vector. NOTE: Java's "Variable Type Parameters" will INVARIABLY produce warnings. // Here, the programmer must include a "@SuppressWarnings("unchecked")" in their method header, // or else he will receive an -Xlint:unchecked warnings. @SuppressWarnings("unchecked") Vector<HTMLNode> html2 = (Vector<HTMLNode>>) FileRW.readObjectFromTextFile("myFile.txt", html.getClass()); // Re-write the loaded HTML FileRW.writeFile(Util.pageToString(html2), "myFile2.html"); // NOTE: Using UNIX "diff -s myFile1.html myFile2.html" produces this: // Files myFile1.html and myFile2.html are identical
- Parameters:
o
- This may be any serializablejava.lang.Object
instance. 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 thisObject
as a text-file.- Throws:
java.io.IOException
- Code:
- Exact Method Body:
FileRW.writeFile(StringParse.objToB64MimeStr(o), fileName);
-
readObjectFromTextFile
public static java.lang.Object readObjectFromTextFile (java.lang.String fileName) throws java.io.IOException
This will read a java serialized, and MIME-Converted, MIME-Safejava.lang.String
from a text file and return theObject
that it represented
NOTE: When multiplejava.lang.Object's
need to be stored, it is sometimes advisable to save them to one of Java's many standardjava.util.Collection
classes, or possibly to ajava.util.List
class, first. Saving multipleObjects's
to ajava.util.Collection
, and then writing that singleCollection Object
to disk can often make code look cleaner.
Keep in mind that all of Java's'java.util.*'
generic data-structures implement theinterface java.io.Serializable
, so writing / serializing an entireVector<Object>
is extremely simple, as long as all of theObject's
contained by theVector
also implementSerializable
(or are 'de-facto' Serializable by the JVM).- Parameters:
fileName
- The name of the file containing the MIME-Encoded Serializedjava.lang.Object
.- Returns:
- The
Object
that had been encoded into the text-file. - Throws:
java.io.IOException
- Code:
- Exact Method Body:
return StringParse.b64MimeStrToObj(loadFileToString(fileName));
-
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.String
from a text file and return theObject
that it represented
NOTE: When multiplejava.lang.Object's
need to be stored, it is sometimes advisable to save them to one of Java's many standardjava.util.Collection
classes, or possibly to ajava.util.List
class, first. Saving multipleObjects's
to ajava.util.Collection
, and then writing that singleCollection Object
to disk can often make code look cleaner.
Keep in mind that all of Java's'java.util.*'
generic data-structures implement theinterface java.io.Serializable
, so writing / serializing an entireVector<Object>
is extremely simple, as long as all of theObject's
contained by theVector
also implementSerializable
(or are 'de-facto' Serializable by the JVM).
This loads the contents of an international website from Europe, and parses the output into aVector<HTMLNode>
. This output is printed to disk, and then it is saved as aB64 MIME-Encode String
and also written to disk. Then thisString
is re-loaded and written out as HTML a second time to verify and ensure that no information was lost in the conversion of the Java'POJO'
intoMIME-Encoded
text.
Example:
// Visit and parse a "Spanish Newspaper" (from Iberia, Spain). Save to HTML Vector. URL url = new URL("https://elpais.com/"); Vector<HTMLNode> html = HTMLPage.getPageTokens(url, false); // Write the HTML out as a MIME-Encoded Java Serialized Object (of the Vector<HTMLNode> // The file itself will resemble 1990's e-mail MIME Messages. FileRW.writeObjectToTextFile(html, "myFile.txt"); // Write the HTML out as a '.html' file FileRW.writeFile(Util.pageToString(html), "myFile1.html"); // Reload the HTML Vector. NOTE: Java's "Variable Type Parameters" will INVARIABLY produce warnings. // Here, the programmer must include a "@SuppressWarnings("unchecked")" in their method header, // or else he will receive an -Xlint:unchecked warnings. @SuppressWarnings("unchecked") Vector<HTMLNode> html2 = (Vector<HTMLNode>>) FileRW.readObjectFromTextFile("myFile.txt", html.getClass()); // Re-write the loaded HTML FileRW.writeFile(Util.pageToString(html2), "myFile2.html"); // NOTE: Using UNIX "diff -s myFile1.html myFile2.html" produces this: // Files myFile1.html and myFile2.html are identical
- Type Parameters:
T
- This Type Parameter informs this method what type of Base-64 Serialized Object is saved within Text File'fileName'
. The returned result of this method will have this type, for convenience to avoid casting theObject
(unless thatObject
is a Java Generic, and you wish to avoid a "Raw Types" warning. See further details inside the explanation about parameter'c'
).- Parameters:
fileName
- The name of the file containing the MIME-Encoded Serializedjava.lang.Object
.c
- This is the type of theObject
expecting to be read from disk. A value for this parameter can always be obtained by referencing thestatic
field'.class'
, which is attached to everyObject
in java.
ALSO: The 'type parameter' (Class<T> c
) is used to indicate the expected type of thejava.lang.Object
that is read, and ultimately returned. This method employs Java's variable-type method syntax. Variable-type parameter<T>
may be anyclass
at all (as long as were Serializable).
Generally, the easiest way to obtain an instance ofClass<T>
is to just cite the field'.class'
that everyjava.lang.Object
contains. For instance, if a user was intending to read aTreeSet
from disk, then specifying that an instance ofClass<TreeSet>
is desired would be as simple as passingTreeSet.class
to this method's'c'
parameter.
GENERIC-ERASURE: Generally because of the concept known as "Generic Erasure" - Variable-Type Parametrized Methods in Java do not function as well as they could. When reading a non-genericObject
from a data-file, the read-operation implemented by this method should work just fine - as long as Java was able to'serialize'
theObject
(which it is able to do most of the time regardless of whether the user has implemented theinterface java.io.Serializable
- by using 'de-facto', automated serialization).
However, if writing, say, an instance ofVector<String>
, the user needs to keep in mind that the stated return-type of this method, when passed the referenceVector.class
, will be of araw-type
'Vector'
, not of typeVector<String>
. Therefore a'cast'
is in order, however, this'cast'
will generate a warning ofunchecked cast
- unless the@SuppressWarnings("unchecked") Annotation
is carefully specified. Notice in the example how theVector.class
parameter, itself, is insufficient to return a aVector<String>
. Here, use acast
, and suppress the compiler warning messages:
Example:
// Generate a Data-Set, and save it to a String-Vector Vector<String> myData = some_data_operation(); // Save this 'Object' (Vector) to disk, in a file named "StringVector.dat" // NOTE: Always passing "true" to the 'ZIP' parameter is usually easiest. // ALSO: We are writing *a single object* (a Vector), even though this Vector is a // collection, it counts as just a single-object in this write. FileRW.writeObjectToFile(myData, "StringVector.dat", true); // To retrieve this Vector - as a Vector<String> reference - use the following // specifier and cast. The "SuppressWarnings" is needed because this is a "generic" // type (Vector<E>) which has a generic-type parameter which IS NOT included information // inside the class 'Vector.class' @SuppressWarnings("unchecked") Vector<String> myData2 = (Vector<String>) FileRW.readObjectFromFile("StringVector.dat", Vector.class, true); // The data-retrieval - AND COMPILER TYPE-CHECKING - should then work all right. // NOTE: This 'extra-cast' is *ONLY* important when serializing a GENERIC-class that // uses the 'ClassName<E>' generic-parameter notation (greater-than and less-than // symbols)... // For serializing 'regular' classes: String, Integer, etc... no such 'extra' cast // is needed - simply use: String.class, Integer.class, etc... // ********************************************************************* // IMPORTANT NOTE: The Same Rational Applies for the 'fromTextFile(...)' // object serializers: // ********************************************************************* FileRW.writeObjectToTextFile(myData, "StringVector.txt"); @SuppressWarnings("unchecked") Vector<String> myData3 = (Vector<String>) FileRW.readObjectFromTextFile("StringVector.txt", Vector.class);
DATA-NOTE: If the file being read did not actually have aVector
which contained only instances ofString
, this could lead non-deterministic results (sometimes called "heap-pollution").- Returns:
- The
Object
that had been encoded into the text-file. - Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.java.lang.ClassNotFoundException
- This exception is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in theCLASSPATH
.- 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's
have been written to a single file. It was better practice to putObject's
in ajava.util.Vector
, and write onejava.util.Vector
during serialization. This, eventually, can became inadequate when downloading large numbers of HTML results, where the need to write a large data-file (intermittently - by saving intermediate results) is needed.- Parameters:
fName
- This is the file-name of the data-file where the serializedObject's
have been stored.ZIP
- If this is set to TRUE, the data will be de-compressed.- Returns:
- A java
ObjectInputStream
- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
return ZIP ? new ObjectInputStream(new GZIPInputStream(new FileInputStream(new File(fName)))) : new ObjectInputStream(new FileInputStream(new File(fName)));
-
getOOS
public static java.io.ObjectOutputStream getOOS(java.lang.String fName, boolean ZIP) throws java.io.IOException
Creates a simpleObjectOutputStream
- usually if multipleObject's
need to be written to a single file. It was better practice to putObject's
in ajava.util.Vector
, and write onejava.util.Vector
during serialization.- Parameters:
fName
- This is the file-name of the data-file where the serializedObject's
will be stored.ZIP
- If this is set to TRUE, the data will be compressed.- Returns:
- A java
ObjectInputStream
- Throws:
java.io.IOException
- If an I/O error has occurred as a result of the file-system or disk operation.- Code:
- Exact Method Body:
return ZIP ? new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(new File(fName)))) : new ObjectOutputStream(new FileOutputStream(new File(fName)));
-
copyFile
public static void copyFile(java.lang.String inFileName, java.lang.String outFileOrDirName, boolean createDirsIfNotExist) throws java.io.IOException
This method will perform a byte-for-byte copy of a file from one location to another.- Parameters:
inFileName
- The name of the input-file. It will be byte-for-byte copied to an output file-name.outFileOrDirName
- The name of the output-file, or the name of the directory where the file shall be moved. If this file already exists and it is a file, not a directory, it will be over-written. If parameter'outFileOrDirName'
names a directory - due to having an endingFile.separator
, but does not appear to name directorie(s) that exist, this method will throw aFileNotFoundException
. However, if parameter'createDirsIfNotExist'
is set to TRUE, even if parameter'outFileOrDirName'
names a directory (by virtue of the fact that it ends with theFile.separator String
) then this method will create the directory tree-structure using the standard Java'sFile.mkdirs()
method.
NOTE: The programmer may provide either a directory-name or a file-name to parameter'outFileOrDirName'
. If the programmer has provided a directory-name instead of a file-name, the moved file will have the same name as the original file ('inFileName'
) had, but it will be located in'outFileOrDirName'
.
BEHAVIOR NOTE: The behavior of this copy operation is generally / mostly the same as the standardUNIX
orMS-DOS
commands'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 to TRUE and the aforementioned situation occurs where the complete-directory tree does not exist, then this method will first attempt to create the directories usingjava.io.File.mkdirs().
- Throws:
java.lang.SecurityException
- If boolean parameter'createDirsIfNotExist'
is TRUE and if the directory named by parameter'outFileName'
does not exist, and if attempting to create such a directory is not permitted by the Operating-System, then this exception shall throw.java.io.IOException
- For any number of fail-causes in reading or writing input stream data. An explanation of all causes of such an operation is beyond the scope of this method-documentation entry.java.io.FileNotFoundException
- If the'inFileName'
is not found, or'outFileOrDirName'
uses a directory path that doesn't exist on the file-system, and parameter'createDirsIfNotExist'
is set to FALSE.SameSourceAndTargetException
- This exception will be thrown if theJava Virtual Machine
ascertains 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.Path
for either the'inFileName'
parameter or the'outFileOrDirName'
, then this exception will be thrown.java.nio.file.NoSuchFileException
- If, after instantiating an instance ofPath
for either thesource
or thetarget
locations, the Java Virtual Machine is unable to build an instance ofPath
using the methodPath.toRealPath()
, then this exception will throw.- Code:
- Exact Method Body:
File f = new File(outFileOrDirName); if (createDirsIfNotExist) f.mkdirs(); if (f.isDirectory()) { if (! outFileOrDirName.endsWith(File.separator)) outFileOrDirName = outFileOrDirName + File.separator; outFileOrDirName = outFileOrDirName + StringParse.fromLastFileSeparatorPos(inFileName); } String inPath = Paths.get(inFileName).toRealPath().toString(); // throws InvalidPathException // throws NoSuchFileException try { if (Paths.get(outFileOrDirName).toRealPath().toString().equals(inPath)) throw new SameSourceAndTargetException( "The Source File Name and the Target Location provided to your copyFile " + "request operation appear to point to the same physical-disk location:\n" + inPath ); } catch (NoSuchFileException e) { } // NOTE: Mostly (but not always) the output file won't exist yet... If it does not, // then we really don't need to worry about over-writing the origina file. // REMEMBER: The only purpose of the above test is to make sure that the source and // target are not the same (to avoid clobbering the original file) FileInputStream fis = new FileInputStream(inFileName); FileOutputStream fos = new FileOutputStream(outFileOrDirName); byte[] b = new byte[5000]; int result = 0; try { while ((result = fis.read(b)) != -1) fos.write(b, 0, result); } finally { fis.close(); fos.flush(); fos.close(); }
-
deleteFiles
public static void deleteFiles(java.lang.String... fileNames)
Convenience Method
Invokes:java.io.File.delete()
- Code:
- Exact Method Body:
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-r
for the commandrm
, or the old Microsoft DOS Command'deltree'
for deleting directories. It simply reuses theclass FileTransfer
NOTE: If this method is used on a UNIX or LINUX platform, then it ought to produce reults that are identical to an invocation ofShell.RM(directoryName, "-r")
. However, if running on Windows, that method invocation would not function because it is a LINUX native API call. This method here is actually platform independent.- Parameters:
directoryName
- This should be a valid directory on the file-system.
WARNING: This command does indeed delete the entire directory-tree of the named directory!reCreateDirectoryOnExit
- This parameter allows the user to create an an empty directory with the same name as the directory that was just deleted, after all of the directory's contents have been deleted. When this parameter is passed a value of TRUE, the equivalent of the UNIX 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 parameter expects an implementation of Java'sinterface java.lang.Appendable
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.StorageWriter
Sends text to System.out
, and saves it, internally.FileWriter, PrintWriter, StringWriter
General purpose java text-output classes FileOutputStream, PrintStream
More general-purpose java text-output classes
IMPORTANT: Theinterface Appendable
requires that the check exceptionIOException
must be caught when using itsappend(CharSequence)
methods.- Returns:
- This shall return a count on the total number of deleted files. Note that when directories are deleted (not files), their deletion shall not count towards the total returned in this integer.
- Throws:
java.lang.IllegalArgumentException
- Throws if theString
provided to parameterdirectoryName
does not name a valid directory on the File-System.java.io.IOException
- Code:
- Exact Method Body:
if (directoryName == null) throw new NullPointerException ("You have provided null to parameter 'directoryName', but this is not allowed here."); File f = new File(directoryName); if (! f.exists()) throw new IllegalArgumentException( "The directory name you have provided: [" + directoryName + "] was not found on the " + "File System. Aborted." ); if (! f.isDirectory()) throw new IllegalArgumentException( "The value you have provided to parameter 'directoryName' was: " + "[" + directoryName + "], but unfortunately this is not the name of a directory on " + "the File System, but rather a file. This is not allowed here." ); // Uses class FileNode to build the directory into Java Memory. // It is possibly of interest to note, that if running this java code on a UNIX or // LINUX platform, this method should perform the exact same operation as an invocation // of Shell.RM(directoryName, "-r"); FileNode fn = FileNode.createRoot(directoryName).loadTree(); int ret = FileTransfer.deleteFilesRecursive(fn, null, null, log); if (reCreateDirectoryOnExit) f.mkdirs(); return ret;
-
readIntsFromFile
public static java.util.stream.IntStream readIntsFromFile (java.lang.String fileName, boolean hasCommasInInts, boolean isCSV, int radix) throws java.io.FileNotFoundException, java.io.IOException
This may read a text-file containing integer data. If this data is a Comma Separated Value'CSV'
text-file, please pass TRUE to the parameter'isCSV'
. If this file contains integers that have commas between digits in groups of three (like'30,000'
) pleas pass TRUE to the parameter'hasCommasInInts'
.
FILE FORMAT: The formatting of the file is not too particular. The'flag'
parameter'isCSV'
merely requires that the individual integers be separated by commas. There may be any number of suchint's
on a particular line, and any number of lines in the file. Blank lines are simply ignored. If'isCSV'
is set to FALSE, all numbers must be separated by some amount of white-space. Multiple numbers may still be placed on a single line (as long as there is white-space between them) even if'isCSV'
is FALSE.
NUMBER FORMAT: The numbers in this text-file must be parse-able by Java'sclass java.lang.Integer
using the 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 to TRUE, this method shall simply remove any comma that is found juxtaposed between two digits before processing any text found in the file.isCSV
- If the text file named by'fileName'
is a Comma Separated Value file, then please pass TRUE to this parameter. If FALSE is passed here, then it is mandatory that the individual numbers inside the text-file are separated by at least one white-space character.
IMPORTANT: If it is decided to set both of the boolean parameters to TRUE - where the integers have commas, and the integers are separated by commas, it is up to the programmer to ensure that the individual numbers, themselves, are not only separated by a comma, but also separated by a space as well.radix
- This is the'radix'
, which is also usually called the number's'base'
that is to be used when parsing the numbers. Since Java'sclass java.lang.Integer
is used to perform the parse, both the'radix'
, and the data found in the text-file must conform to the Java methodInteger.parseInt(String s, int radix)
.
NOTE: This parameter may not be ignored. If the numbers in the text-file are to be interpreted as standard'decimal'
(Base 10) numbers, then the user should simply pass the constant'10'
to this parameter.- Returns:
- This method shall return a
java.util.stream.IntStream
consisting of the integers that were found within the text-file provided by'fileName'
.
NOTE: An instance ofIntStream
is 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 pass TRUE to the parameter'isCSV'
. If this file contains integers that have commas between digits in groups of three (like'30,000'
) pleas pass TRUE to the parameter'hasCommasInLongs'
.
FILE FORMAT: The formatting of the file is not too particular. The'flag'
parameter'isCSV'
merely requires that the individuallong
integers be separated by commas. There may be any number of suchlong's
on a particular line, and any number of lines in the file. Blank lines are simply ignored. If'isCSV'
is set to FALSE, all numbers must be separated by some amount of white-space. Multiple numbers may still be placed on a single line (as long as there is white-space between them) even if'isCSV'
is FALSE.
NUMBER FORMAT: The numbers in this text-file must be parse-able by Java'sclass java.lang.Long
using the methodLong.parseLong(String s, int radix)
- Parameters:
fileName
- This should contain the file-name which itself contains a list of'long'
integers. Theselong
integers 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 along
integer. For instance the number'98765'
, to a reader, is often represented as'98,765'
. When this parameter is set to TRUE, this method shall simply remove any comma that is found juxtaposed between two digits before processing any text found in the file.isCSV
- If the text file named by'fileName'
is a Comma Separated Value file, then please pass TRUE to this parameter. If FALSE is passed here, then it is mandatory that the individual numbers inside the text-file are separated by at least one white-space character.
IMPORTANT: If it is decided to set both of the boolean parameters to TRUE - where thelong
integers have commas, and thelong
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 Long
is 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)
.
NOTE: This parameter may not be ignored. If the numbers in the text-file are to be interpreted as standard'decimal'
(Base 10) numbers, then the user should simply pass the constant'10'
to this parameter.- Returns:
- This method shall return a
java.util.stream.LongStream
consisting of thelong
-integers that were found within the text-file provided by'fileName'
.
NOTE: An instance ofLongStream
is 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 pass TRUE to the parameter'isCSV'
. If this file containsdouble's
that have commas between digits in groups of three (like'30,000,000,00'
) pleas pass TRUE to the parameter'hasCommasInDoubles'
.
FILE FORMAT: The formatting of the file is not too particular. The'flag'
parameter'isCSV'
merely requires that the individualdouble
values be separated by commas. There may be any number of suchdouble's
on a particular line, and any number of lines in the file. Blank lines are simply ignored. If'isCSV'
is set to FALSE, all numbers must be separated by some amount of white-space. Multiple numbers may still be placed on a single line (as long as there is white-space between them) even if'isCSV'
is FALSE.
NUMBER FORMAT: The numbers in this text-file must be parseable by Java'sclass java.lang.Double
using the methodDouble.parseDouble(String s)
- Parameters:
fileName
- This should contain the file-name which itself contains a list of'double'
values. Thesedouble's
may 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 adouble
value. For instance the number'98765.01'
, to a reader, can be represented as'98,765.01'
. When this parameter is set to TRUE, this method shall simply remove any comma that is found juxtaposed between two digits before processing any text found in the file.isCSV
- If the text file named by'fileName'
is a Comma Separated Value file, then please pass TRUE to this parameter. If FALSE is passed here, then it is mandatory that the individual numbers inside the text-file are separated by at least one white-space character.
IMPORTANT: If it is decided to set both of the boolean parameters to TRUE - where thedouble
values have commas, and thedouble
values are separated by commas, it is up to the programmer to ensure that the individual numbers, themselves, are not only separated by a comma, but also separated by a space as well.- Returns:
- This method shall return a
java.util.stream.DoubleStream
consisting of thedouble
-values that were found within the text-file provided by'fileName'
.
NOTE: An instance ofDoubleStream
is 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.
NOTE: Unlike Java'sFileOutputStream.write(...)
method, theread(...)
that's provided by that same exact class is more difficult to use, and 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's
to skip before appending abyte
into 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.
IMPORTANT: The meaning of the value in parameter'offset'
is very different from the meaning of a parameter by that exact same name, except in 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's
will continue to be copied into this array until precisely'len'
bytes have been copied.
IMORTANT: The user may provide any negative number to this parameter, and the read process will simply begin at position'offset'
, and continue reading until the End of the File has been reached.- Returns:
- Returns a
byte[]
-array, with a length of (parameter)'len'
bytes. - Throws:
java.io.FileNotFoundException
- Classjava.io.FileInputStream
will throw aFileNotFoundException
if that class is passed a'fileName'
that does not exist, or is a file-name that represents a directory not a file.java.lang.SecurityException
- If a security manager exists and itscheckRead
method denies read access to the file.java.io.IOException
- TheFileInputStream
instance, and thejava.io.File
instance 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 + len
is larger than the size of the underlying file. - An invocation of the method
File.length()
returns zero, indicating that the file is either unreadable, non-existant, or possibly empty.
- 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 anEOF
earlier than expected (for unforseen reasons), thenEOFException
would throw.- Code:
- Exact Method Body:
// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // EXCEPTION CHECKS // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (offset < 0) throw new IllegalArgumentException ("The value of offset (" + offset + ") is negative."); if (len == 0) throw new IllegalArgumentException ("A value of zero was provided to parameter 'len.' This is not allowed"); File f = new File(fileName); try (FileInputStream fis = new FileInputStream(f)) { long fileLen = f.length(); // A file-name that points to a completely empty file was passed to parameter 'fileName' // **OR** the operating system returned 0 for some other error-related reason. // According to the Java-Doc explanation, a '0' returned value might mean there were // errors when trying to access the file. if (fileLen == 0) throw new FileSizeException( "Calling java.io.File.length() returned 0 for the file-name that was " + "provided to this method:\n[" + fileName + "]. This might mean that the file " + "does not exist, or has other issues.", 0 ); // The file would end before we have even started reading bytes - after having skipped // 'offset' nmber of initial bytes. if (offset > fileLen) throw new FileSizeException( "The value of offset (" + offset + ") is larger than the size of the binary " + "file, which only had size (" + fileLen + ").", fileLen ); // If 'len' was passed a negative value, that value is actually meaningless - and was // just used to indicate that reading the entire file starting at byte # 'offset' is // what the user is requesting. if (len > 0) // This simply checks how many bytes the file would need to have to provide for // reading from 'offset' up until 'offset + len' if ((offset + len) > fileLen) throw new FileSizeException( "The file [" + fileName + "] apparently has a size of [" + fileLen + "], " + "but the offset (" + offset + ") and the length (" + len + ") that was " + "requested sum to (" + (offset+len) + "), which is greater than that size.", fileLen ); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // More Exception Checks: Check what the size of the returned byte[] array will be // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Negative-Length means that bytes are read until an EOF occurrs if (len < 0) { long bytesToRead = fileLen - offset; if (bytesToRead > Integer.MAX_VALUE) throw new FileSizeException( "This file has [" + fileLen + "] bytes of data, and even with an offset of " + '[' + offset + "], there are still " + bytesToRead + " bytes of data to " + "place into the array. This value is larger than Integer.MAX_VALUE " + "(" + Integer.MAX_VALUE + ").", fileLen ); else len = (int) bytesToRead; } // A Positive length means that exactly the value inside input-parameter 'len' need to // be placed into the returned byte[] array. else if (len > Integer.MAX_VALUE) throw new FileSizeException( "This file has [" + fileLen + "] bytes of data, which is larger than " + "Integer.MAX_VALUE (" + Integer.MAX_VALUE + ").", fileLen ); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // FIRST, if there is a NON-ZERO OFFSET, then exactly OFFSET bytes must be skipped // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** int failedReads = 0; long bytesSkipped = 0; int totalBytesSkipped = 0; int bytesRemaining = offset; // NOTE: This loop is skipped, immediately / automatically, if indeed 'offset' is zero while (totalBytesSkipped < offset) if ((bytesSkipped = fis.skip(bytesRemaining)) == 0) { if (failedReads++ == 10) throw new IOException( "There have 10 repeated attempts to read the file's data, but all " + "attempts have resulted in empty-reads with zero bytes being retrieved " + "from disk." ); } else { // I don't see why this should happen, but it will be left here, just in // case Java screws up. if (bytesSkipped > bytesRemaining) throw new InternalError( "This error is being thrown because the Java Virtual Machine has " + "skipped past the end of the requested offset. This has occured while " + "calling FileInputStream.skip(offset)." ); // NOTE: I am *FULLY AWARE* this is redundant, but the variable names are // the only thing that is very readable about this method. totalBytesSkipped += bytesSkipped; bytesRemaining -= bytesSkipped; } // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // THEN, Read the bytes from the file // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** byte[] retArr = new byte[len]; int arrPos = 0; // This one was already defined / declared in the previous part. Initialize it, but // don't re-declare it. bytesRemaining = len; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // This loop exits when all (requested) bytes have been read, or EOFException! // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** while (bytesRemaining > 0) { int bytesRead = fis.read(retArr, arrPos, bytesRemaining); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Case 1: The EOF Marker was reached, before filling up the response-array // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (bytesRead == -1) if (bytesRemaining > 0) throw new EOFException( "The end of file '" + fileName + "' was reached before " + len + " bytes were read. Only " + arrPos + " bytes were read." ); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Yes, this seems redundant, but it's just the way it is // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // arrPos ==> 0 ... retArr.length (retArr.length => input-param 'len') // bytesRemaining ==> 'len' ... 0 arrPos += bytesRead; bytesRemaining -= bytesRead; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Case 2: Exactly the appropriate number of bytes were read. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** if (arrPos == retArr.length) return retArr; // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Case 3: This should not be reachable! // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // // Java's FileInputStream.read method is supposed to stop when it has read // 'bytesRemaining' number of bytes! if (arrPos > retArr.length) throw new UnreachableError(); } // One of the cases inside the loop body must fire before the loop ever actually exits, // unless I'm missing something! throw new UnreachableError(); }
-
readClass
public static java.lang.Class<?> readClass (java.lang.String classFileName, java.lang.String... possibleClassNames) throws java.io.IOException
Attempts to read ajava.lang.Class
from a class-file.
NOTE: It is not neccessarily always knownst to the programmer what the Full-Package Class-Name of theclass
that's inside the class-file actually is.- Parameters:
classFileName
- The name of any class-file on the file-system.possibleClassNames
- If the exact Full-Package Name of the class being read is known, then that ought to be the onlyString
passed 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 to read a class file, and then ask that class-file either:- What the name of the
Class
in the Class-File is? - What the name of the
Package
being used in that Class-File is?
So, for now, a Var-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.Class
that was contained by the Class-File. - Throws:
java.io.IOException
- Java may throw several exceptions while attempting to load the'.class'
file into abyte[]
array. Such exceptions may includeIOException
,SecurityException
,FileNotFoundException
etc...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', thisRuntimeException
is thrown as a nicely worded error message is provided.- Code:
- Exact Method Body:
// *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Load the entire '.class' file into a byte[] array. // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Now read the bytes directly into a byte[] array, courtesy of Torello.Java.FileRW byte[] byteArray = readBinary(classFileName); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Create a ClassLoader - and convert "byte[]" into "Class<?> summarySorterClass" // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // NOTE: The commented lines below will not work if there is a "Package Name" given to the // class (in the '.java' file). It is better to just read the raw class-file bytes // into a Java byte[] array. SPECIFICALLY, if class is not inside of a directory // that is PRECISELY-CONSISTENT with the full-path package+class name, then the class // loader listed below will FAIL. (NOTE: If the package+class name is consisten, // then a programmer wouldn't need ANY OF THIS, and could simply call the normal // "Class.forName(fullPackageClassName)" to get the class!) // // ClassLoader cl = new URLClassLoader(new URL[] { new URL("file://" + path) }); // Class<?> ret = cl.loadClass(className); // // HOWEVER: Creating a new ClassLoader instance that accepts the byte-array (thereby // exporting the 'protected' method defineClass) *DOES* work. class ByteClassLoader extends ClassLoader { public Class<?> defineClass(String name, byte[] classBytes) { return defineClass(name, classBytes, 0, classBytes.length); } } ByteClassLoader cl = new ByteClassLoader(); Class<?> ret = null; StringBuilder sb = new StringBuilder(); // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** // Make attempts to convert the byte[] array into a java.lang.Class // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** for (String fullClassName : possibleClassNames) try { return cl.defineClass(fullClassName, byteArray); } catch (NoClassDefFoundError e) { String errorMessage = e.getMessage(); if (errorMessage != null) sb.append(errorMessage + '\n'); } throw new TypeNotPresentException( "The Class-File: [" + classFileName + "] seems to have been successfully read, but " + "none of the user provided Canonical-Class Names (including a package) were " + "consistent with the actual name of the Class/Type inside that class file. Below " + "are listed the exception-messages received, which include both the actual/complete " + "canonical class-name, along with your user-provided guesses. Errors Saved:\n" + StrIndent.indent(sb.toString(), 4), null );
-
-