What is the result?

Given the existing destination file, a source file only 1000 bytes long, and the code fragment:

public void process (String source, String destination) {

try (InputStream fis = new FileInputStream(source);

OutputStream fos = new FileOutputStream(destination)

) {

byte [] buff = new byte[2014];

int i;

while ((i = fis.read(buff)) != -1) {

fos.write(buff,0,i); // line ***

}

} catch (IOException e) {

System.out.println(e.getClass());

}

}

What is the result?

Given the existing destination file, a source file only 1000 bytes long, and the code fragment:

public void process (String source, String destination) {

try (InputStream fis = new FileInputStream(source);

OutputStream fos = new FileOutputStream(destination)

) {

byte [] buff = new byte[2014];

int i;

while ((i = fis.read(buff)) != -1) {

fos.write(buff,0,i); // line ***

}

} catch (IOException e) {

System.out.println(e.getClass());

}

}

What is the result?

A.
Overrides the content of the destination file with the source file content

B.
Appends the content of the source file to the destination file after a new line

C.
Appends the content of the source file to the destination file without a break in the flow

D.
Throws a runtime exception at line***

Explanation:
The whole of theFileInputStreamwill be read (see ** below). The content of theFileInputStreamwill overwrite the destination file (see *** below).

*A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

**FileInputStream.read(byte[] b)
Reads up to b.length bytes of data from this input stream into an array of bytes.

Parameters:
b – the buffer into which the data is read.
Returns:
the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

***FileOutputStream
You can construct a FileOutputStream object by passing a string containing a path name or a File object.
You can also specify whether you want to append the output to an existing file.

public FileOutputStream (String path)
public FileOutputStream (String path, boolean append)
public FileOutputStream (File file)
public FileOutputStream (File file, boolean append)

With the first and third constructors, if a file by the specified name already exists, the file will be overwritten. To append to an existing file, pass true to the second or fourth constructor.

Reference:Class FileInputStream

Reference:Class FileOutputStream



Leave a Reply 1

Your email address will not be published. Required fields are marked *