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
Do'stlaringiz bilan baham: