In this lab you will experiment with FileReader / FileWriter objects, as well as StreamReader / StreamWriter objects. Create an application project, Lab4. Accept all of the defaults except Project Location. Go to File view on your project and copy UnixDBAEssentials.pdf into your Lab5 folder. Return to the Project view.
Let’s start with some simple File objects. First, create a File object (in) for an existing file, “UnixDBAEssentials.pdf”. Then create a couple File objects for files that don’t exist: “FileTest.pdf” (fOut) and “StreamTest.pdf” (sOut). Use the File methods to see if the DBA Essentials file exists and if we can read from it. Write the results of these queries to Standard Out.
Then create a FileReader object for “UnixDBAEssentials.pdf”, and a FileWriter object for the other file. Also create a char buffer to hold the reads and writes. Declare all variables outside of the try/catch block that you will eventually need. The actual constructors will occur within a try/catch block.
char cBuffer = new char; // 2K char array to hold our IO
fw =new FileWriter(wOut);
fr = new FileReader(in);
We will use the int
read(charcbuf, intoff, intlen)
method of the Reader to read our data, and the void write(charcbuf, intoff, intlen) of the Writer object to output our data.
Read from the input file and write to the output file. Close both files when you’re done and check your directory. The output file should have the same length as the input file. Try to open the file that you created and see what happens.
Now add the code to create a couple of Stream objects to read and write the same file. Change the buffer from char to byte. Use a try with resources for this part.
byte bBuffer = new byte; // this will be our array for output
fis = new FileInputStream(in);
fos = new FileOutputStream(sOut);
We will use the
int read(byteb, intoff, intlen) to read the file, and the
void write(byteb, intoff, intlen) to write the file.
Try the appropriate read/write code in order to copy the file. Once again, try to open the output file.
Submit your completed code, along with a comment that shows the size of each of your output files and explains why they’re different. Try to open each file and explain why one opens and one doesn’t.