首页 > > 详细

辅导MINS325 FileReader and FileWriter讲解留学生Java

Java。

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.

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.

1
2
3
char[] cBuffer = new char[2048]; // 2K char array to hold our IO
fw =new FileWriter(wOut);
fr = new FileReader(in);

 

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 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.

1
2
3
4
byte[] bBuffer = new byte[2048]; // this will be our array for output
// Resources:
fis = new FileInputStream(in);
fos = new FileOutputStream(sOut);

 

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 they’re different. Try to open each file and explain why one opens and one doesn’t.

联系我们
  • QQ:99515681
  • 邮箱:99515681@qq.com
  • 工作时间:8:00-21:00
  • 微信:codinghelp
热点标签

联系我们 - QQ: 99515681 微信:codinghelp
程序辅导网!