Java Programing laungage

Java Input Output Projects

Java I/O Project 1

Java Input Output Examples

Java Input Output Examples

IO Interview Questions And Answers
More interview questions and answers

Explain how to read a line of input at a time.

Input from the console is read from the System.in object and is then wrapped by an InputStreamReader which reads one character at a time

When do we need to flush an output stream?

If any bytes that are previously written and have been buffered by the implementation of the output stream then such bytes need to be immediatel written to their intended destination


Explain the difference between runnable and extends in java?

We can use Extend Thread class only when the class

Explain the term thread safety and synchronization?

The term Thread safety means each method in a multithreaded

How can I append an existing file in Java?

Appending data to a file is a fairly common task. You\'ll be surprised to know that there was no support for file appending in JDK1.02, and developers supporting that platform are forced to re-write the entire file to a temporary file, and then overwrite the original. As most users support either JDK1.1 or the Java 2 platform, you\'ll probably be able to use the following FileOutputStream constructor to append data: 


public FileOutputStream(String name,

                        boolean append)

                 throws FileNotFoundException

Parameters:

name - the system-dependent file name

append - if true, then bytes will be written to the end of the file rather than the beginning

For example, to append the file \'autoexec.bat\' to add a new path statement on a Wintel machine, you could do the following: 

How can I read from, and write to, files in Java?

Stand-alone applications written in Java can access the local file-system, but applets executing under the control of a browser cannot. With this in mind, lets take a look at two simple applications that write a line of text to a file, and read it back.

import java.io.*;

public class MyFirstFileWritingApp

{

// Main method

public static void main (String args[])

{

// Stream to write file

FileOutputStream fout;

try

{

   // Open an output stream

   fout = new FileOutputStream (\"myfile.txt\");


   // Print a line of text

   new PrintStream(fout).println (\"hello world!\");


   // Close our output stream

   fout.close();

}

// Catches any error conditions

catch (IOException e)

{

System.err.println (\"Unable to write to file\");

System.exit(-1);

}

}

}

How do I connect a Reader to an InputStream?

This is a very common question - after all, there aren\'t any SocketReaders, or PipedReaders. You need something to bridge the gap between a Reader, and an InputStream. That\'s where InputStreamReader comes into play.

InputStreamReader is a reader that can be connected to any InputStream - even filtered input streams such as DataInputStream, or BufferedInputStream. Here\'s an example that shows InputStreamReader in action.

// Connect a BufferedReader, to an InputStreamReader which is connected to

// an InputStream called \'in\'.

BufferedReader reader = new BufferedReader ( new InputStreamReader ( in ) );

You can do the same with an OutputStream to a Writer (see OutputStreamWriter for more information).

Why can\'t my applet read or write to files?

Applets execute under the control of a web browser. Netscape and Internet Explorer impose a security restriction, that prohibits access to the local filesystem by applets. While this may cause frustration for developers, this is an important security feature for the end-user. Without it, applets would be free to modify the contents of a user\'s hard-drive, or to read its contents and send this information back over a network.


Digitally signed applets can request permission to access the local filesystem, but the easiest way around the problem is to read and write to remote files located on a network drive.

For example: in conjunction with a CGI script or servlet, you could send HTTP requests to store and retrieve data.


When should I use an InputStream, and when should I use a Reader?

This can be confusing, particularly if you\'re already familiar with InputStream, and keep getting deprecated API warning messages. Let me simplify it for you.

If you\'re reading data, such as bytes of information, you are best off to use InputStreams and DataInputStream in particular.

If you\'re reading in text, and want to be able to call a readLine() method, its best to use Readers, and BufferedReader in particular.

So what\'s the difference? Well, DataInputStream\'s readLine() method is deprecated, because of problems with this method. Readers offer an alternative - though placing a readLine() method in a BufferedReader still seems a little odd to me. Whether its buffered or not has little to do with the fact it can read lines of text - but its easy enough to live with.


Why do threads block on I/O?

Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

When invoking format, what is the best way to indicate a new line?

Use the %n conversion  the n escape is not platform independent!

What class would you use to read a few pieces of data that are at known positions near the end of a large file?

RandomAccessFile.

How would you determine the MIME type of a file?

The Files.probeContentType method uses the platform\'s underlying file type detector to evaluate and return the MIME type.

What class in the java.util.zip package gives you access to the entries in a ZIP archive and allows you to read those entries through a stream?

ZipInputStream. This class implements an input stream filter for reading files in the ZIP file format

How would you append data to the end of a file? Show the constructor for the class you would use and explain your answer?

RandomAccessFile.

Here\'s a quick answer: Use the FileWriter and BufferedWriter classes to append data to the end of the text file. Here is the FileWriter constructor, you pass in true to write to the file in append mode:


FileWriter writer = new FileWriter (String filename, boolean append);

An alternate answer is to use RandomAccessFile and skip to the end of the file and start writing:


RandomAccessFile file = new RandomAccessFile(datafile, \"rw\");

file.skipBytes((int)file.length()); //skip to the end of the file

file.writeBytes(\"Add this text to the end of datafile\"); //write at the end of the file

file.close();

How can you improve the performance of the following code? Explain your answer and show the new line(s) of code?

int i;

URL url = new URL(\"http://java.sun.com/\");

URLConnection javaSite = url.openConnection();

InputStream input = javaSite.getInputStream();

InputStreamReader reader = new InputStreamReader(input);

while ((i = reader.read()) != -1) {

System.out.print(i);

}

Is the following code legal? try { } finally { }

Yes, its legal and very useful A try statement does not have to have a catch block if it has a finally block. If the code in the try statement has multiple exit points and no associated catch clauses, the code in the finally block is executed no matter how the try block is exited. Thus it makes sense to provide a finally block whenever there is code that must always be executed. This include resource recovery code, such as the code to close I/O streams

What is wrong with using this type of exception handler?

This handler catches exceptions of type Exception; therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.

Is there anything wrong with this exception handler as written? Will this code compile? try { } catch (Exception e) { } catch (ArithmeticException a) { }

This first handler catches exceptions of type Exception; therefore, it catches any exception, including ArithmeticException. The second handler could never be reached. This code will not compile.

What will happen when you attempt to compile and run this code? import java.io.*; class Base{ public static void amethod()throws FileNotFoundException{} } public class ExcepDemo extends Base{ public static void main(String argv[]){ ExcepDemo e = new ExcepDemo(); } public static void amethod(int i)throws IOException{} private boolean ExcepDemo(){ try{ DataInputStream din = new DataInputStream(System.in); System.out.println(Pausing); din.readChar(); System.out.println(Continuing); this.amethod(); return true; }catch(IOException ioe) {} finally{ System.out.println(finally); } return false; } } 1) Compilation and run with no output. 2) Compilation and run with output of Pausing, Continuing and finally 3) Runtime error caused by amethod declaring Exception not in base version 4) Compile and run with output of Pausing and Continuing after a key is hit

(1)

Is there a way to make static method not available according to some runtime condition?

Yes! See the following code snippet:

class UtilClass{

static boolean condition;

static {

}

public static void staticMethod() throws Exception{

if (!condition) {

throw new Exception(method not supported for);

}

}

}

What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.