Requirement
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.
Lets 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 dont 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.
1 | char[] cBuffer = new char[2048]; // 2K char array to hold our IO |
We will use the int read(char[]cbuf, intoff, intlen)
method of the Reader to read our data, and the void write(char[]cbuf, 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 youre 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.
1 | byte[] bBuffer = new byte[2048]; // this will be our array for output |
We will use the int read(byte[]b, intoff, intlen)
to read the file, and the void write(byte[]b, 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 theyre different. Try to open each file and explain why one opens and one doesnt.