Author Topic:   Boone #38; File I/O
Howard Stern
ranch hand
posted March 14, 2000 11:22 AM             
Hi I have been a keen follower of your site but I did not participate till now, so here goes:
Question 38: What does the following code do?

File f = new File("hello.test");
FileOutputStream out = new FileOutputStream(f);


Select the one right answer.


a)Create a new file named "hello.test" if it does not yet exist. It also opens the file so you can write to it and read from it.
b)Create a new file named "hello.test" if it does not yet exist. The file is not opened.
c)Open a file named "hello.test" so that you can write to it and read from it, but does not create the file if it does not yet exist.
d)Open a file named "hello.test" so that you can write to it but cannot read from it.
e)Create an object that you can now use to create and open the file named "hello.test," and write to and read from the file.

Answer was:
Question 38: a. The first line creates a File object that represents the file. By creating a FileOutputStream, you create the file if it does not yet exist, and open that file for reading and writing. (See chapter 11.)

There are no methods in the FileOutputStream class to read from a file. Doesn't it open a file just to write and not to read? If it opens for a read, how do you read the contents of the file.

maha anna
bartender
posted March 14, 2000 12:08 PM             
File f = new File("hello.test");
FileOutputStream out = new FileOutputStream(f);
These 2 statements together opens/creates if it does not exists a phycical file called "hello.test" in the current dir where the java program is executed.
If the file already exists means, It keeps the file pointer at the start of the file and overwrites the original content of the file. If you want to append to an already existing file you have to use this type of constructor. new FileOutputStream (String filename, boolean append) and the append has to be true.

FileOutputStream is connected to a sink of bytes. It is used to write to the sink. It is not possible to read from it.

So the closest answer I fins is d). Eventhough it does not say anythig about the creation part, what it says is true.

regds
maha anna

Tony Alicea
sheriff
posted March 14, 2000 12:13 PM             
Yes I noticed that too when I was practicing. The error is not corrected in the errata so I suggest you chuck it up as a BAD question.

The file is opened for writing.

Jim Yingst
sheriff
posted March 14, 2000 12:34 PM             
Yup - only D is correct. So, I'm moving this to "Mock Exam Errata" since it's exactly what we want there. Thanks "Howard"!

|