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


Write a code sample that creates a file in the path


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

Write a code sample that creates a file in the path
/usr/test.txt.
Answer:
The following code will create a file test.txt within the /usr/
directory:
try {
File txtFile = new File(“/usr/test.txt”); // Line 1
txtFile.createNewFile(); // Line 2
} catch (IOException exp) {
}
In the above code, when Line 1 is executed, an object txtFile
is created in memory and when Line 2 is executed, the file
test.txt is created inside the folder /usr/.


178.
179.
Explain the FileWriter class with a code sample.
Answer:
FileWriter class is used to write characters or Strings to a file
without having to convert them to a byte array.
They are usually wrapped within PrintWriter or BufferedWriter
which provides performance improvement and more methods for
writing data. The following code demonstrates a FileWriter:
try {
File txtFile = new File(“/usr/CoreJava.txt”);
FileWriter myFileWriter = new FileWriter(txtFile);
myFileWriter.write(“Line 1 \n Line 2 \n”); // Line 1
myFileWriter.flush();
myFileWriter.close();
} catch (IOException exp) {
}
In the above code, when Line 1 is executed, the write()
method writes the content into the file CoreJava.txt.
Write a code snippet that reads the content in the file
/usr/CoreJava.txt using a FileReader and displays the
output in the console.
Answer:
The following code demonstrates reading the content in the
specified file using a FileReader and displaying the output on
the console:
try {
File txtFile = new File(“F:/CoreJava.txt”);


180.
181.
char [] totalChar = new char[1000];
FileReader myFileReader = new FileReader(txtFile);
myFileReader.read(totalChar); //Line 1
for(char readChar: totalChar) {//Line 2
System.out.print(readChar);
}
myFileReader.close();
}
catch (IOException exp) {
}
When Line 1 is executed, the read() method reads the content
from the file and into the totalChar array. The for loop at line 2
then prints the contents of the array to the console

Download 1.52 Mb.

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




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