Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Explain with a code sample how you can create a


Download 1.52 Mb.
Pdf ko'rish
bet68/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   64   65   66   67   68   69   70   71   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Explain with a code sample how you can create a
directory on the file system.
Answer:
There is a method called mkdir() on the File class that creates a
directory corresponding to the specified file object. The following
code uses this method to create a directory in the file system:
File myDirectory = new File(“/usr/mydir”); //1
myDirectory.mkdir(); //2
Line 1 creates a file object. Line 2 invokes the mkdir() method
to creates an actual directory.
Explain what happens when the following code is
compiled and executed.
File myDirectory = new File(“/usr/JavaCodes”);


182.
File myNewFile = new
File(“/usr/JavaCodes/CoreJava.txt”); //line 1
myNewFile.createNewFile();
Answer:
The above code throws an IOException. This is because the
directory /usr/JavaCodes/ is not created, only a file object
myDirectory corresponding to it is created. In order for the code
to work, you need to add the following line of code before Line 1:
myDirectory.mkdir();
Write a code sample that demonstrates the PrintWriter
class.
Answer:
The PrintWriter is a specialization of the Writer class can be
used to write formatted representations of objects. The following
code demonstrates how the PrintWriter can be used to write
a String:
File myNewFile = new File(“/usr/CoreJava.txt”);
PrintWriter myPrintWriter = new PrintWriter(myNewFile);
//Line 1
myPrintWriter.println(“This gets inserted into the
File”); //Line 2
myPrintWriter.close(); //Line 3
In the above code, when Line 1 is executed, the file CoreJava.txt
is created inside the folder /usr/.
When Line 2 is executed, the println() method writes the
String specified in the file CoreJava.txt and terminates the line.



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   64   65   66   67   68   69   70   71   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling