Question
stringlengths 1
113
| Answer
stringlengths 22
6.98k
|
|---|---|
Can you provide the Methods of FileReader class?
|
Methods of FileReader class
Method: int read()
Description: It is used to return a character in ASCII form. It returns -1 at the end of file.
Method: void close()
Description: It is used to close the FileReader class.
|
Can you give me the Java FileReader Example?
|
In this example, we are reading the data from the text file testout.txt using Java FileReader class.
package com.javatpoint;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
|
What is Java BufferedWriter Class?
|
Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance fast. It inherits Writer class. The buffering characters are used for providing the efficient writing of single arrays, characters, and strings.
|
What is Java BufferedWriter Class declaration?
|
Let's see the declaration for Java.io.BufferedWriter class:
public class BufferedWriter extends Writer
|
Can you give me an Example of Java BufferedWriter?
|
Let's see the simple example of writing the data to a text file testout.txt using Java BufferedWriter.
package com.javatpoint;
import java.io.*;
public class BufferedWriterExample {
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("D:\\testout.txt");
BufferedWriter buffer = new BufferedWriter(writer);
buffer.write("Welcome to javaTpoint.");
buffer.close();
System.out.println("Success");
}
}
Output:
success
testout.txt:
Welcome to javaTpoint.
|
What is Java BufferedReader Class?
|
Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class.
|
What is Java BufferedReader class declaration?
|
Let's see the declaration for Java.io.BufferedReader class:
public class BufferedReader extends Reader
|
Can you provide the Java BufferedReader class constructors?
|
Constructors of Java BufferedReader class
Constructor: BufferedReader(Reader rd)
Description: It is used to create a buffered character input stream that uses the default size for an input buffer.
Constructor: BufferedReader(Reader rd, int size)
Description: It is used to create a buffered character input stream that uses the specified size for an input buffer.
|
Can you give me the Java BufferedReader class methods?
|
Methods of Java BufferedReader class
Method: int read()
Description: It is used for reading a single character.
Method: int read(char[] cbuf, int off, int len)
Description: It is used for reading characters into a portion of an array.
Method: boolean markSupported()
Description: It is used to test the input stream support for the mark and reset method.
Method: String readLine()
Description: It is used for reading a line of text.
Method: boolean ready()
Description: It is used to test whether the input stream is ready to be read.
Method: long skip(long n)
Description: It is used for skipping the characters.
Method: void reset()
Description: It repositions the stream at a position the mark method was last called on this input stream.
Method: void mark(int readAheadLimit)
Description: It is used for marking the present position in a stream.
Method: void close()
Description: It closes the input stream and releases any of the system resources associated with the stream.
|
Can you provide the Java BufferedReader Example?
|
In this example, we are reading the data from the text file testout.txt using Java BufferedReader class.
package com.javatpoint;
import java.io.*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
|
What is Java CharArrayReader Class?
|
The CharArrayReader is composed of two words: CharArray and Reader. The CharArrayReader class is used to read character array as a reader (stream). It inherits Reader class.
|
What is Java CharArrayReader class declaration?
|
Let's see the declaration for Java.io.CharArrayReader class:
public class CharArrayReader extends Reader
|
Can you give me the Java CharArrayReader class methods?
|
Methods of Java CharArrayReader class
Method: int read()
Description: It is used to read a single character
Method: int read(char[] b, int off, int len)
Description: It is used to read characters into the portion of an array.
Method: boolean ready()
Description: It is used to tell whether the stream is ready to read.
Method: boolean markSupported()
Description: It is used to tell whether the stream supports mark() operation.
Method: long skip(long n)
Description: It is used to skip the character in the input stream.
Method: void mark(int readAheadLimit)
Description: It is used to mark the present position in the stream.
Method: void reset()
Description: It is used to reset the stream to a most recent mark.
Method: void close()
Description: It is used to closes the stream.
|
Can you provide an Example of CharArrayReader Class?
|
Let's see the simple example to read a character using Java CharArrayReader class.
package com.javatpoint;
import java.io.CharArrayReader;
public class CharArrayExample{
public static void main(String[] ag) throws Exception {
char[] ary = { 'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't' };
CharArrayReader reader = new CharArrayReader(ary);
int k = 0;
// Read until the end of a file
while ((k = reader.read()) != -1) {
char ch = (char) k;
System.out.print(ch + " : ");
System.out.println(k);
}
}
}
Output:
j : 106
a : 97
v : 118
a : 97
t : 116
p : 112
o : 111
i : 105
n : 110
t : 116
|
What is Java CharArrayWriter Class?
|
The CharArrayWriter class can be used to write common data to multiple files. This class inherits Writer class. Its buffer automatically grows when data is written in this stream. Calling the close() method on this object has no effect.
|
What is Java CharArrayWriter class declaration?
|
Let's see the declaration for Java.io.CharArrayWriter class:
public class CharArrayWriter extends Writer
|
Can you give me the Java CharArrayWriter class Methods?
|
Methods of Java CharArrayWriter class
Method: int size()
Description: It is used to return the current size of the buffer.
Method: char[] toCharArray()
Description: It is used to return the copy of an input data.
Method: String toString()
Description: It is used for converting an input data to a string.
Method: CharArrayWriter append(char c)
Description: It is used to append the specified character to the writer.
Method: CharArrayWriter append(CharSequence csq)
Description: It is used to append the specified character sequence to the writer.
Method: CharArrayWriter append(CharSequence csq, int start, int end)
Description: It is used to append the subsequence of a specified character to the writer.
Method: void write(int c)
Description: It is used to write a character to the buffer.
Method: void write(char[] c, int off, int len)
Description: It is used to write a character to the buffer.
Method: void write(String str, int off, int len)
Description: It is used to write a portion of string to the buffer.
Method: void writeTo(Writer out)
Description: It is used to write the content of buffer to different character stream.
Method: void flush()
Description: It is used to flush the stream.
Method: void reset()
Description: It is used to reset the buffer.
Method: void close()
Description: It is used to close the stream.
|
Can you provide an Example of CharArrayWriter Class?
|
In this example, we are writing a common data to 4 files a.txt, b.txt, c.txt and d.txt.
package com.javatpoint;
import java.io.CharArrayWriter;
import java.io.FileWriter;
public class CharArrayWriterExample {
public static void main(String args[])throws Exception{
CharArrayWriter out=new CharArrayWriter();
out.write("Welcome to javaTpoint");
FileWriter f1=new FileWriter("D:\\a.txt");
FileWriter f2=new FileWriter("D:\\b.txt");
FileWriter f3=new FileWriter("D:\\c.txt");
FileWriter f4=new FileWriter("D:\\d.txt");
out.writeTo(f1);
out.writeTo(f2);
out.writeTo(f3);
out.writeTo(f4);
f1.close();
f2.close();
f3.close();
f4.close();
System.out.println("Success...");
}
}
Output
Success…
After executing the program, you can see that all files have common data: Welcome to javaTpoint.
a.txt:
Welcome to javaTpoint
b.txt:
Welcome to javaTpoint
c.txt:
Welcome to javaTpoint
d.txt:
Welcome to javaTpoint
|
What is Java PrintStream Class?
|
The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the data so there is no need to call flush() method. Moreover, its methods don't throw IOException.
|
What is Java PrintStream Class declaration?
|
Let's see the declaration for Java.io.PrintStream class:
public class PrintStream extends FilterOutputStream implements Closeable. Appendable
|
Can you provide the Methods of PrintStream class?
|
void print(boolean b) - It prints the specified boolean value.
void print(char c) - It prints the specified char value.
void print(char[] c) - It prints the specified character array values.
void print(int i) - It prints the specified int value.
void print(long l) - It prints the specified long value.
void print(float f) - It prints the specified float value.
void print(double d) - It prints the specified double value.
void print(String s) - It prints the specified string value.
void print(Object obj) - It prints the specified object value.
void println(boolean b) - It prints the specified boolean value and terminates the line.
void println(char c) - It prints the specified char value and terminates the line.
void println(char[] c) - It prints the specified character array values and terminates the line.
void println(int i) - It prints the specified int value and terminates the line.
void println(long l) - It prints the specified long value and terminates the line.
void println(float f) - It prints the specified float value and terminates the line.v
void println(double d) - It prints the specified double value and terminates the line.
void println(String s) - It prints the specified string value and terminates the line.
void println(Object obj) - It prints the specified object value and terminates the line.
void println() - It terminates the line only.
void printf(Object format, Object... args) - It writes the formatted string to the current stream.
void printf(Locale l, Object format, Object... args) - It writes the formatted string to the current stream.
void format(Object format, Object... args) - It writes the formatted string to the current stream using specified format.
void format(Locale l, Object format, Object... args) - It writes the formatted string to the current stream using specified format.
|
Can you give me an Example of java PrintStream class?
|
In this example, we are simply printing integer and string value.
package com.javatpoint;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamTest{
public static void main(String args[])throws Exception{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt ");
PrintStream pout=new PrintStream(fout);
pout.println(2016);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
fout.close();
System.out.println("Success?");
}
}
Output
Success...
The content of a text file testout.txt is set with the below data
2016
Hello Java
Welcome to Java
|
Can you give me an Example of printf() method using java PrintStream class?
|
Let's see the simple example of printing integer value by format specifier using printf() method of java.io.PrintStream class.
class PrintStreamTest{
public static void main(String args[]){
int a=19;
System.out.printf("%d",a); //Note: out is the object of printstream
}
}
Output
19
|
What is Java PrintWriter class?
|
Java PrintWriter class is the implementation of Writer class. It is used to print the formatted representation of objects to the text-output stream.
|
What is Java PrintWriter class declaration?
|
Let's see the declaration for Java.io.PrintWriter class:
public class PrintWriter extends Writer
|
Can you give me the Methods of PrintWriter class?
|
void println(boolean x) - It is used to print the boolean value.
void println(char[] x) - It is used to print an array of characters.
void println(int x) - It is used to print an integer.
PrintWriter append(char c) - It is used to append the specified character to the writer.
PrintWriter append(CharSequence ch) - It is used to append the specified character sequence to the writer.
PrintWriter append(CharSequence ch, int start, int end) - It is used to append a subsequence of specified character to the writer.
boolean checkError() - It is used to flushes the stream and check its error state.
protected void setError() - It is used to indicate that an error occurs.
protected void clearError() - It is used to clear the error state of a stream.
PrintWriter format(String format, Object... args) - It is used to write a formatted string to the writer using specified arguments and format string.
void print(Object obj) - It is used to print an object.
void flush() - It is used to flushes the stream.
void close() - It is used to close the stream.
|
Can you provide the Java PrintWriter Example?
|
Let's see the simple example of writing the data on a console and in a text file testout.txt using Java PrintWriter class.
package com.javatpoint;
import java.io.File;
import java.io.PrintWriter;
public class PrintWriterExample {
public static void main(String[] args) throws Exception {
//Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter(System.out);
writer.write("Javatpoint provides tutorials of all technology.");
writer.flush();
writer.close();
//Data to write in File using PrintWriter
PrintWriter writer1 =null;
writer1 = new PrintWriter(new File("D:\\testout.txt"));
writer1.write("Like Java, Spring, Hibernate, Android, PHP etc.");
writer1.flush();
writer1.close();
}
}
Outpt
Javatpoint provides tutorials of all technology.
The content of a text file testout.txt is set with the data Like Java, Spring, Hibernate, Android, PHP etc.
|
What is Java OutputStreamWriter?
|
OutputStreamWriter is a class which is used to convert character stream to byte stream, the characters are encoded into byte using a specified charset. write() method calls the encoding converter which converts the character into bytes. The resulting bytes are then accumulated in a buffer before being written into the underlying output stream. The characters passed to write() methods are not buffered. We optimize the performance of OutputStreamWriter by using it with in a BufferedWriter so that to avoid frequent converter invocation.
|
Can you provide the Java OutputStreamWriter Constructor?
|
OutputStreamWriter(OutputStream out) - It creates an OutputStreamWriter that uses the default character encoding.
OutputStreamWriter(OutputStream out, Charset cs) - It creates an OutputStreamWriter that uses the given charset.
OutputStreamWriter(OutputStream out, CharsetEncoder enc) - It creates an OutputStreamWriter that uses the given charset encoder.
OutputStreamWriter(OutputStream out, String charsetName) - It creates an OutputStreamWriter that uses the named charset.
|
Can you give me the Java OutputStreamWriter Methods?
|
Modifier and type: void
Method: close()
Description: It closes the stream, flushing it first.
Modifier and type: void
Method: flush()
Description: It flushes the stream
Modifier and type: String
Method: getEncoding()
Description: It returns the name of the character encoding being used by this stream.
Modifier and type: void
Method: write(char[] cbuf, int off, int len)
Description: It writes a portion of an array of characters.
Modifier and type: void
Method: write(int c)
Description: It writes a single character.
Modifier and type: void
Method: write(String str, int off, int len)
Description: It writes a portion of a string.
|
Can you provide the Java OutputStreamWriter example?
|
public class OutputStreamWriterExample {
public static void main(String[] args) {
try {
OutputStream outputStream = new FileOutputStream("output.txt");
Writer outputStreamWriter = new OutputStreamWriter(outputStream);
outputStreamWriter.write("Hello World");
outputStreamWriter.close();
} catch (Exception e) {
e.getMessage();
}
}
}
Output:
output.txt file will contains text "Hello World"
|
What is Java InputStreamReader?
|
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
|
Can you give me the Java InputStreamReader constructor?
|
Constructor name: InputStreamReader(InputStream in)
Description: It creates an InputStreamReader that uses the default charset.
Constructor name: InputStreamReader(InputStream in, Charset cs)
Description: It creates an InputStreamReader that uses the given charset.
Constructor name: InputStreamReader(InputStream in, CharsetDecoder dec)
Description: It creates an InputStreamReader that uses the given charset decoder
Constructor name: InputStreamReader(InputStream in, String charsetName)
Description: It creates an InputStreamReader that uses the named charset.
|
Can you provide the Java InputStreamReader method?
|
Modifier and type: void
Method: close()
Description: It closes the stream and releases any system resources associated with it.
Modifier and type: String
Method: getEncoding()
Description: It returns the name of the character encoding being used by this stream.
Modifier and type:int
Method: read()
Description: It reads a single character.
Modifier and type: int
Method: read(char[] cbuf, int offset, int length)
Description: It reads characters into a portion of an array.
Modifier and type: boolean
Method: ready()
Description: It tells whether this stream is ready to be read.
|
Can you give me the Java InputStreamReader example?
|
public class InputStreamReaderExample {
public static void main(String[] args) {
try {
InputStream stream = new FileInputStream("file.txt");
Reader reader = new InputStreamReader(stream);
int data = reader.read();
while (data != -1) {
System.out.print((char) data);
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
I love my country
The file.txt contains text "I love my country" the InputStreamReader
reads Character by character from the file
|
What is Java PushbackInputStream Class?
|
Java PushbackInputStream class overrides InputStream and provides extra functionality to another input stream. It can unread a byte which is already read and push back one byte.
|
What is Java PushbackInputStream Class declaration?
|
Let's see the declaration for java.io.PushbackInputStream class:
public class PushbackInputStream extends FilterInputStream
|
Can you give me the Java PushbackInputStream Class methods?
|
It is used to test if the input stream support mark and reset method.
int available() - It is used to return the number of bytes that can be read from the input stream.
int read() - It is used to read the next byte of data from the input stream.
boolean markSupported()
void mark(int readlimit) - It is used to mark the current position in the input stream.
long skip(long x) - It is used to skip over and discard x bytes of data.
void unread(int b) - It is used to pushes back the byte by copying it to the pushback buffer.
void unread(byte[] b) - It is used to pushes back the array of byte by copying it to the pushback buffer.
void reset() - It is used to reset the input stream.
void close() - It is used to close the input stream.
|
Can you provide an Example of PushbackInputStream class?
|
import java.io.*;
public class InputStreamExample {
public static void main(String[] args)throws Exception{
String srg = "1##2#34###12";
byte ary[] = srg.getBytes();
ByteArrayInputStream array = new ByteArrayInputStream(ary);
PushbackInputStream push = new PushbackInputStream(array);
int i;
while( (i = push.read())!= -1) {
if(i == '#') {
int j;
if( (j = push.read()) == '#'){
System.out.print("**");
}else {
push.unread(j);
System.out.print((char)i);
}
}else {
System.out.print((char)i);
}
}
}
}
Output:
1**2#34**#12
|
What is Java PushbackReader Class?
|
Java PushbackReader class is a character stream reader. It is used to pushes back a character into stream and overrides the FilterReader class.
|
What is Java PushbackReader Class declaration?
|
Let' s see the declaration for java.io.PushbackReader class:
public class PushbackReader extends FilterReader
|
Can you give me the Java PushbackReader Class methods?
|
int read() - It is used to read a single character.
void mark(int readAheadLimit) - It is used to mark the present position in a stream.
boolean ready() - It is used to tell whether the stream is ready to be read.
boolean markSupported() - It is used to tell whether the stream supports mark() operation.
long skip(long n) - It is used to skip the character.
void unread (int c) - It is used to pushes back the character by copying it to the pushback buffer.
void unread (char[] cbuf) - It is used to pushes back an array of character by copying it to the pushback buffer.
void reset() - It is used to reset the stream
void close() - It is used to close the stream.
|
Can you provide an Example of PushbackReader class?
|
import java.io.*;
public class ReaderExample{
public static void main(String[] args) throws Exception {
char ary[] = {'1','-','-','2','-','3','4','-','-','-','5','6'};
CharArrayReader reader = new CharArrayReader(ary);
PushbackReader push = new PushbackReader(reader);
int i;
while( (i = push.read())!= -1) {
if(i == '-') {
int j;
if( (j = push.read()) == '-'){
System.out.print("#*");
}else {
push.unread(j); // push back single character
System.out.print((char)i);
}
}else {
System.out.print((char)i);
}
}
}
}
Output
1#*2-34#*-56
|
What is Java StringWriter Class?
|
Java StringWriter class is a character stream that collects output from string buffer, which can be used to construct a string. The StringWriter class inherits the Writer class.
In StringWriter class, system resources like network sockets and files are not used, therefore closing the StringWriter is not necessary.
|
What is Java StringWriter class declaration?
|
Let's see the declaration for Java.io.StringWriter class:
public class StringWriter extends Writer
|
Can you give me the Methods of StringWriter class?
|
void write(int c) - It is used to write the single character.
void write(String str) - It is used to write the string.
void write(String str, int off, int len) - It is used to write the portion of a string.
void write(char[] cbuf, int off, int len) - It is used to write the portion of an array of characters.
String toString() - It is used to return the buffer current value as a string.
StringBuffer getBuffer() - It is used t return the string buffer.
StringWriter append(char c) - It is used to append the specified character to the writer.
StringWriter append(CharSequence csq)- It is used to append the specified character sequence to the writer.
StringWriter append(CharSequence csq, int start, int end)- It is used to append the subsequence of specified character sequence to the writer.
void flush() - It is used to flush the stream.
void close() - It is used to close the stream.
|
Can you provide the Java StringWriter Example?
|
Let's see the simple example of StringWriter using BufferedReader to read file data from the stream.
import java.io.*;
public class StringWriterExample {
public static void main(String[] args) throws IOException {
char[] ary = new char[512];
StringWriter writer = new StringWriter();
FileInputStream input = null;
BufferedReader buffer = null;
input = new FileInputStream("D://testout.txt");
buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int x;
while ((x = buffer.read(ary)) != -1) {
writer.write(ary, 0, x);
}
System.out.println(writer.toString());
writer.close();
buffer.close();
}
}
testout.txt:
Javatpoint provides tutorial in Java, Spring, Hibernate, Android, PHP etc.
Output:
Javatpoint provides tutorial in Java, Spring, Hibernate, Android, PHP etc
|
What is Java StringReader Class?
|
Java StringReader class is a character stream with string as a source. It takes an input string and changes it into character stream. It inherits Reader class.
In StringReader class, system resources like network sockets and files are not used, therefore closing the StringReader is not necessary.
|
What is Java StringReader class declaration?
|
Let's see the declaration for Java.io.StringReader class:
public class StringReader extends Reader
|
Can you give me the Methods of StringReader class?
|
int read() - It is used to read a single character.
int read(char[] cbuf, int off, int len) -It is used to read a character into a portion of an array.
boolean ready() - It is used to tell whether the stream is ready to be read.
boolean markSupported() - It is used to tell whether the stream support mark() operation.
long skip(long ns)-It is used to skip the specified number of character in a stream
void mark(int readAheadLimit) - It is used to mark the mark the present position in a stream.
void reset()- It is used to reset the stream.
void close()- It is used to close the stream.
|
Can you provide the Java StringReader Example?
|
import java.io.StringReader;
public class StringReaderExample {
public static void main(String[] args) throws Exception {
String srg = "Hello Java!! \nWelcome to Javatpoint.";
StringReader reader = new StringReader(srg);
int k=0;
while((k=reader.read())!=-1){
System.out.print((char)k);
}
}
}
Output:
Hello Java!!
Welcome to Javatpoint.
|
What is Java - PipedWriter?
|
The PipedWriter class is used to write java pipe as a stream of characters. This class is used generally for writing text. Generally PipedWriter is connected to a PipedReader and used by different threads.
|
What is Java - PipedWriter constructor?
|
Constructor: PipedWriter()
Description: It creates a piped writer that is not yet connected to a piped reader.
Constructor: PipedWriter(PipedReader snk)
Description: It creates a piped writer connected to the specified piped reader.
|
Can you give me the Java - PipedWriter method?
|
Modifier and Type: void
Method: close()
Description: It closes this piped output stream and releases any system resources associated with this stream.
Modifier and Type: void
Method: connect(PipedReader snk)
Description: It connects this piped writer to a receiver.
Modifier and Type: void
Method:flush()
Description: It flushes this output stream and forces any buffered output characters to be written out.
Modifier and Type: void
Method: write(char[] cbuf, int off, int len)
Description: It writes len characters from the specified character array starting at offset off to this piped output stream.
Modifier and Type: void
Method: write(int c)
Description: It writes the specified char to the piped output stream.
|
Can you provide the Java - PipedWriter example?
|
import java.io.PipedReader;
import java.io.PipedWriter;
public class PipeReaderExample2 {
public static void main(String[] args) {
try {
final PipedReader read = new PipedReader();
final PipedWriter write = new PipedWriter(read);
Thread readerThread = new Thread(new Runnable() {
public void run() {
try {
int data = read.read();
while (data != -1) {
System.out.print((char) data);
data = read.read();
}
} catch (Exception ex) {
}
}
});
Thread writerThread = new Thread(new Runnable() {
public void run() {
try {
write.write("I love my country\n".toCharArray());
} catch (Exception ex) {
}
}
});
readerThread.start();
writerThread.start();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Output:
I love my country
|
What is Java - PipedReader?
|
The PipedReader class is used to read the contents of a pipe as a stream of characters. This class is used generally to read text.
PipedReader class must be connected to the same PipedWriter and are used by different threads.
|
Can you provide the Java - PipedReader constructor?
|
Constructor: PipedReader(int pipeSize)
Description: It creates a PipedReader so that it is not yet connected and uses the specified pipe size for the pipe's buffer.
Constructor: PipedReader(PipedWriter src)
Description: It creates a PipedReader so that it is connected to the piped writer src.
Constructor: PipedReader(PipedWriter src, int pipeSize)
Description: It creates a PipedReader so that it is connected to the piped writer src and uses the specified pipe size for the pipe's buffer.
Constructor: PipedReader()
Description: It creates a PipedReader so that it is not yet connected.
|
Can you give me the Java - PipedReader method?
|
Modified and type: void
Method: close()
Description: It closes this piped stream and releases any system resources associated with the stream.
Modified and type: void
Method: connect(PipedWriter src)
Description: It causes this piped reader to be connected to the piped writer src.
Modified and type: int
Method: read()
Description: It reads the next character of data from this piped stream.
Modified and type: int
Method: read(char[] cbuf, int off, int len)
Description: It reads up to len characters of data from this piped stream into an array of characters.
Modified and type: boolean
Method: ready()
Description: It tells whether this stream is ready to be read.
|
Can you provide Java - PipedReader example?
|
import java.io.PipedReader;
import java.io.PipedWriter;
public class PipeReaderExample2 {
public static void main(String[] args) {
try {
final PipedReader read = new PipedReader();
final PipedWriter write = new PipedWriter(read);
Thread readerThread = new Thread(new Runnable() {
public void run() {
try {
int data = read.read();
while (data != -1) {
System.out.print((char) data);
data = read.read();
}
} catch (Exception ex) {
}
}
});
Thread writerThread = new Thread(new Runnable() {
public void run() {
try {
write.write("I love my country\n".toCharArray());
} catch (Exception ex) {
}
}
});
readerThread.start();
writerThread.start();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Output:
I love my country
|
What is Java FilterWriter?
|
Java FilterWriter class is an abstract class which is used to write filtered character streams.
The sub class of the FilterWriter should override some of its methods and it may provide additional methods and fields also.
|
What is Java FilterWriter fields?
|
Modifier: protected
Type: Writer
Field: out
Description: The underlying character-output stream.
|
Can you provide the Java FilterWriters constructor?
|
Modifier: protected
Constructor: FilterWriter(Writer out)
Description:It creates InputStream class Object
|
Can you give me the Java FilterWriter method?
|
Modifier and Type : void
Method: close()
Description:It closes the stream, flushing it first.
Modifier and Type :void
Method:flush()
Description:It flushes the stream.t
Modifier and Type : void
Method: write(char[] cbuf, int off, int len)
Description:It writes a portion of an array of characters.
Modifier and Type :void
Method:write(int c)
Description:It writes a single character.
Modifier and Type :void
Method: write(String str, int off, int len)
Description:It writes a portion of a string.
|
Can you provide the Java FilterWriter example?
|
import java.io.*;
class CustomFilterWriter extends FilterWriter {
CustomFilterWriter(Writer out) {
super(out);
}
public void write(String str) throws IOException {
super.write(str.toLowerCase());
}
}
public class FilterWriterExample {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("Record.txt");
CustomFilterWriter filterWriter = new CustomFilterWriter(fw);
filterWriter.write("I LOVE MY COUNTRY");
filterWriter.close();
FileReader fr = new FileReader("record.txt");
BufferedReader bufferedReader = new BufferedReader(fr);
int k;
while ((k = bufferedReader.read()) != -1) {
System.out.print((char) k);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
i love my country
While running the current program if the current working directory does not contain the file, a new file is created and CustomFileWriter will write the text "I LOVE MY COUNTRY" in lowercase to the file.
|
What is Java FilterReader?
|
Java FilterReader is used to perform filtering operation on reader stream. It is an abstract class for reading filtered character streams.
The FilterReader provides default methods that passes all requests to the contained stream. Subclasses of FilterReader should override some of its methods and may also provide additional methods and fields.
|
What is Java FilterReader Field?
|
Modifier: protected
Type: Reader
Field: in
Description: The underlying character-input stream.
|
Can you provide the Java FilterReader constructor?
|
Modifier: protected
Constructor: FilterReader(Reader in)
Description: It creates a new filtered reader.
|
Can you give me the Java FilterReader method?
|
Modifier and Type:void
Method: close()
Description: It closes the stream and releases any system resources associated with it.
Modifier and Type:void
Method: mark(int readAheadLimit)
Description: It marks the present position in the stream.
Modifier and Type: boolean
Method: markSupported()
Description: It tells whether this stream supports the mark() operation.
Modifier and Type: boolean
Method: ready()
Description: It tells whether this stream is ready to be read.
Modifier and Type:int
Method: read()
Description: It reads a single character.
Modifier and Type:int
Method: read(char[] cbuf, int off, int len)
Description: It reads characters into a portion of an array.
Modifier and Type: void
Method: reset()
Description: It resets the stream.
Modifier and Type: long
Method: skip(long n)
Description: It skips characters.
|
Can you provide the Java FilterReader example?
|
In this example, we are using "javaFile123.txt" file which contains "India is my country" text in it. Here, we are converting whitespace with question mark '?'.
import java.io.*;
class CustomFilterReader extends FilterReader {
CustomFilterReader(Reader in) {
super(in);
}
public int read() throws IOException {
int x = super.read();
if ((char) x == ' ')
return ((int) '?');
else
return x;
}
}
public class FilterReaderExample {
public static void main(String[] args) {
try {
Reader reader = new FileReader("javaFile123.txt");
CustomFilterReader fr = new CustomFilterReader(reader);
int i;
while ((i = fr.read()) != -1) {
System.out.print((char) i);
}
fr.close();
reader.close();
} catch (Exception e) {
e.getMessage();
}
}
}
Output:
India?is?my?country
|
What is Java File Class?
|
The File class is an abstract representation of file and directory pathname. A pathname can be either absolute or relative.
The File class have several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files, listing the contents of a directory etc.
|
Can you provide the Java File Class fields?
|
Modifier:static
Type:String
Field:pathSeparator
Description: It is system-dependent path-separator character, represented as a string for convenience.
Modifier:static
Type:char
Field:pathSeparatorChar
Description: It is system-dependent path-separator character.
Modifier:static
Type:String
Field:separator
Description: It is system-dependent default name-separator character, represented as a string for convenience.
Modifier:static
Type:char
Field:separatorChar
Description: It is system-dependent default name-separator character
|
Can you give the Java File Class constructors?
|
Constructor: File(File parent, String child)
Description: It creates a new File instance from a parent abstract pathname and a child pathname string.
Constructor: File(String pathname)
Description: It creates a new File instance by converting the given pathname string into an abstract pathname.
Constructor: File(String parent, String child)
Description: It creates a new File instance from a parent pathname string and a child pathname string.
Constructor: File(URI uri)
Description: It creates a new File instance by converting the given file: URI into an abstract pathname.
|
Can you give the Java File Class methods?
|
Modifier and Type: static File
Method: createTempFile(String prefix, String suffix)
Description: It creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Modifier and Type:boolean
Method: createNewFile()
Description: It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.
Modifier and Type:boolean
Method: canWrite()
Description: It tests whether the application can modify the file denoted by this abstract pathname.String[]
Modifier and Type:boolean
Method: canExecute()
Description: It tests whether the application can execute the file denoted by this abstract pathname.
Modifier and Type:boolean
Method: canRead()
Description: It tests whether the application can read the file denoted by this abstract pathname.
Modifier and Type:boolean
Method: isAbsolute()
Description: It tests whether this abstract pathname is absolute.
Modifier and Type:boolean
Method: isDirectory()
Description:It tests whether the file denoted by this abstract pathname is a directory.
Modifier and Type: boolean
Method: isFile()
Description: It tests whether the file denoted by this abstract pathname is a normal file.
Modifier and Type:String
Method: getName()
Description: It returns the name of the file or directory denoted by this abstract pathname.
Modifier and Type:String
Method: getParent()
Description: It returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
Modifier and Type:Path
Method: toPath()
Description: It returns a java.nio.file.Path object constructed from the this abstract path.
Modifier and Type:URI
Method: toURI()
Description: It constructs a file: URI that represents this abstract pathname.
Modifier and Type: File[]
Method: listFiles()
Description: It returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname
Modifier and Type: long
Method: getFreeSpace()
Description: It returns the number of unallocated bytes in the partition named by this abstract path name.
Modifier and Type: String[]
Method: list(FilenameFilter filter)
Description: It returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.
Modifier and Type: boolean
Method: mkdir()
Description: It creates the directory named by this abstract pathname.
|
Java FileDescriptor
|
FileDescriptor class serves as an handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. The handle can be err, in or out.
The FileDescriptor class is used to create a FileInputStream or FileOutputStream to contain it.
|
What is Java FileDescriptor field?
|
Modifier:static
Type:FileDescriptor
Field:err
Description: A handle to the standard error stream.
Modifier:static
Type:FileDescriptor
Field:in
Description:A handle to the standard input stream.
Modifier:static
Type:FileDescriptor
Field:out
Description: A handle to the standard output stream.
|
Can you give me the Java FileDescriptor constructor?
|
Constructor: FileDescriptor()
Description: Constructs an (invalid) FileDescriptor object.
|
Can you give me the Java FileDescriptor method?
|
Modifier and Type: void
Method: sync()
Description: It force all system buffers to synchronize with the underlying device.
Modifier and Type: boolean
Method: valid()
Description: It tests if this file descriptor object is valid.
|
Can you provide the Java FileDescriptor example?
|
import java.io.*;
public class FileDescriptorExample {
public static void main(String[] args) {
FileDescriptor fd = null;
byte[] b = { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58 };
try {
FileOutputStream fos = new FileOutputStream("Record.txt");
FileInputStream fis = new FileInputStream("Record.txt");
fd = fos.getFD();
fos.write(b);
fos.flush();
fd.sync();// confirms data to be written to the disk
int value = 0;
// for every available bytes
while ((value = fis.read()) != -1) {
char c = (char) value;// converts bytes to char
System.out.print(c);
}
System.out.println("\nSync() successfully executed!!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
0123456789:
Sync() successfully executed!!
Record.txt:
0123456789:
|
What is Java - RandomAccessFile?
|
This class is used for reading and writing to random access file. A random access file behaves like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor we do the read write operations. If end-of-file is reached before the desired number of byte has been read than EOFException is thrown. It is a type of IOException.
|
Can you give me the Java - RandomAccessFile constructor?
|
Constructor: RandomAccessFile(File file, String mode)
Description: Creates a random access file stream to read from, and optionally to write to, the file specified by the File argument.
Constructor: RandomAccessFile(String name, String mode)
Description: Creates a random access file stream to read from, and optionally to write to, a file with the specified name.
|
Can you give me the Java - RandomAccessFile method?
|
Modifier and Type:void
Method: close()
Description: It closes this random access file stream and releases any system resources associated with the stream.
Modifier and Type: FileChannel
Method: getChannel()
Description: It returns the unique FileChannel object associated with this file.
Modifier and Type: int
Method: readInt()
Description: It reads a signed 32-bit integer from this file.
Modifier and Type: String
Method: readUTF()
Description: It reads in a string from this file.
Modifier and Type: void
Method: seek(long pos)
Description: It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
Modifier and Type: void
Method: writeDouble(double v)
Description: It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that long value to the file as an eight-byte quantity, high byte first.
Modifier and Type: void
Method:writeFloat(float v)
Description:It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the file as a four-byte quantity, high byte first.
Modifier and Type:void
Method: write(int b)
Description: It writes the specified byte to this file.
Modifier and Type: int
Method: read()
Description: It reads a byte of data from this file.
Modifier and Type:long
Method: length()
Description: It returns the length of this file.
Modifier and Type:void
Method: seek(long pos)
Description: It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
|
Can you provide the Java - RandomAccessFile example?
|
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
The myFile.TXT contains text "This class is used for reading and writing to random access file."
after running the program it will contains
This class is used for reading I love my country and my peoplele.
|
What is Java Scanner?
|
Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default. It provides many methods to read and parse various primitive values.
The Java Scanner class is widely used to parse text for strings and primitive types using a regular expression. It is the simplest way to get input in Java. By the help of Scanner in Java, we can get input from the user in primitive types such as int, long, double, byte, float, short, etc.
The Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
The Java Scanner class provides nextXXX() methods to return the type of value such as nextInt(), nextByte(), nextShort(), next(), nextLine(), nextDouble(), nextFloat(), nextBoolean(), etc. To get a single character from the scanner, you can call next().charAt(0) method which returns a single character
|
What is Java Scanner Class Declaration?
|
public final class Scanner
extends Object
implements Iterator<String>
|
How to get Java Scanner?
|
To get the instance of Java Scanner which reads input from the user, we need to pass the input stream (System.in) in the constructor of Scanner class. For Example:
Scanner in = new Scanner(System.in);
To get the instance of Java Scanner which parses the strings, we need to pass the strings in the constructor of Scanner class. For Example:
Scanner in = new Scanner("Hello Javatpoint");
|
Can you give me the Java Scanner Class Constructors?
|
Sn:1
Constructor: Scanner(File source)
Description: It constructs a new Scanner that produces values scanned from the specified file.
Sn:2
Constructor: Scanner(File source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified file.
Sn:3
Constructor: Scanner(InputStream source)
Description: It constructs a new Scanner that produces values scanned from the specified input stream.
Sn:4
Constructor: Scanner(InputStream source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified input stream
Sn:5
Constructor: Scanner(Readable source)
Description: It constructs a new Scanner that produces values scanned from the specified source.
Sn:6
Constructor: Scanner(String source)
Description: It constructs a new Scanner that produces values scanned from the specified string.
Sn:7
Constructor: Scanner(ReadableByteChannel source)
Description: It constructs a new Scanner that produces values scanned from the specified channel.
Sn:8
Constructor: Scanner(ReadableByteChannel source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified channel.
Sn:9
Constructor: Scanner(Path source)
Description: It constructs a new Scanner that produces values scanned from the specified file.
Sn:10
Constructor: Scanner(Path source, String charsetName)
Description: It constructs a new Scanner that produces values scanned from the specified file.
|
Can you give me the ava Scanner Class Methods?
|
Sn:1
Modifier and Type: void
Method: close()
Description: It is used to close this scanner..
Sn:2
Modifier and Type: pattern
Method: delimiter()
Description: It is used to get the Pattern which the Scanner class is currently using to match delimiters.
Sn:3
Modifier and Type: Stream<MatchResult>
Method: findAll()
Description: It is used to find a stream of match results that match the provided pattern string.
Sn:4
Modifier and Type: String
Method: findInLine()
Description:It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Sn:5
Modifier and Type: string
Method: findWithinHorizon()
Description:It is used to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Sn:6
Modifier and Type: boolean
Method: hasNext()
Description: It returns true if this scanner has another token in its input.
Sn:7
Modifier and Type: boolean
Method: hasNextBigDecimal()
Description: It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method or not.
Sn:8
Modifier and Type: boolean
Method: hasNextBigInteger()
Description: It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method or not.
Sn:9
Modifier and Type: boolean
Method: hasNextBoolean()
Description: It is used to check if the next token in this scanner's input can be interpreted as a Boolean using the nextBoolean() method or not.
Sn:10
Modifier and Type: boolean
Method: hasNextByte()
Description:It is used to check if the next token in this scanner's input can be interpreted as a Byte using the nextBigDecimal() method or not.
Sn:11
Modifier and Type: boolean
Method: hasNextDouble()
Description:It is used to check if the next token in this scanner's input can be interpreted as a BigDecimal using the nextByte() method or not.
Sn:12
Modifier and Type: boolean
Method: hasNextFloat()
Description: It is used to check if the next token in this scanner's input can be interpreted as a Float using the nextFloat() method or not.
Sn:13
Modifier and Type: boolean
Method: hasNextInt()
Description:It is used to check if the next token in this scanner's input can be interpreted as an int using the nextInt() method or not.
Sn:14
Modifier and Type: boolean
Method: hasNextLine()
Description: It is used to check if there is another line in the input of this scanner or not.
Sn:15
Modifier and Type: boolean
Method: hasNextLong()
Description: It is used to check if the next token in this scanner's input can be interpreted as a Long using the nextLong() method or not.
Sn:16
Modifier and Type: boolean
Method: hasNextShort()
Description:It is used to check if the next token in this scanner's input can be interpreted as a Short using the nextShort() method or not.
Sn:17
Modifier and Type: IOException
Method: ioException()
Description:It is used to get the IOException last thrown by this Scanner's readable
Sn:18
Modifier and Type: Locale
Method: locale()
Description: It is used to get a Locale of the Scanner class.
Sn:19
Modifier and Type: MatchResult
Method: match()
Description: It is used to get the match result of the last scanning operation performed by this scanner.
Sn:20
Modifier and Type: String
Method: next()
Description: It is used to get the next complete token from the scanner which is in use.
Sn:21
Modifier and Type: BigDecimal
Method: nextBigDecimal()
Description: It scans the next token of the input as a BigDecimal.
Sn:22
Modifier and Type: BigInteger
Method: nextBigInteger()
Description: It scans the next token of the input as a BigInteger.
Sn:23
Modifier and Type: boolean
Method: nextBoolean()
Description:It scans the next token of the input into a boolean value and returns that value.
Sn:24
Modifier and Type: byte
Method: nextByte()
Description: It scans the next token of the input as a byte.
Sn:25
Modifier and Type: double
Method: nextDouble()
Description: It scans the next token of the input as a double.
Sn:26
Modifier and Type: float
Method: nextFloat()
Description: It scans the next token of the input as a float.
Sn:27
Modifier and Type: int
Method: nextInt()
Description: It scans the next token of the input as an Int.
Sn:28
Modifier and Type: String
Method: nextLine()
Description: It is used to get the input string that was skipped of the Scanner object.
Sn:29
Modifier and Type: long
Method: nextLong()
Description: It scans the next token of the input as a long.
Sn:30
Modifier and Type: short
Method: nextShort()
Description: It scans the next token of the input as a short.
Sn:31
Modifier and Type: int
Method: radix()
Description: It is used to get the default radix of the Scanner use.
Sn:32
Modifier and Type: void
Method: remove()
Description: It is used when remove operation is not supported by this implementation of Iterator.
Sn:33
Modifier and Type: Scanner
Method: reset()
Description: It is used to reset the Scanner which is in use.
Sn:34
Modifier and Type: Scanner
Method: skip()
Description:It skips input that matches the specified pattern, ignoring delimiters
Sn:35
Modifier and Type: Stream<String>
Method: tokens()
Description:It is used to get a stream of delimiter-separated tokens from the Scanner object which is in use.
Sn:36
Modifier and Type: String
Method: toString()
Description:It is used to get the string representation of Scanner using.
Sn:37
Modifier and Type: Scanner
Method: useDelimiter()
Description: It is used to set the delimiting pattern of the Scanner which is in use to the specified pattern.
Sn:38
Modifier and Type: Scanner
Method: useLocale()
Description: It is used to sets this scanner's locale object to the specified locale.
Sn:39
Modifier and Type: Scanner
Method: useRadix()
Description: It is used to set the default radix of the Scanner which is in use to the specified radix.
|
Can you provide Java Scanner Class example?
|
Let's see a simple example of Java Scanner where we are getting a single input from the user. Here, we are asking for a string through in.nextLine() method.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
Enter your name: sonoo jaiswal
Name is: sonoo jaiswal
|
What is Serialization and Deserialization in Java?
|
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called deserialization where byte-stream is converted into an object. The serialization and deserialization process is platform-independent, it means you can serialize an object on one platform and deserialize it on a different platform.
For serializing the object, we call the writeObject() method of ObjectOutputStream class, and for deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
|
What are the Advantages of Java Serialization?
|
It is mainly used to travel object's state on the network (that is known as marshalling).
|
What is java.io.Serializable interface?
|
Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. The Cloneable and Remote are also marker interfaces.
The Serializable interface must be implemented by the class whose object needs to be persisted.
The String class and all the wrapper classes implement the java.io.Serializable interface by default.
Let's see the example given below:
Student.java
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
In the above example, Student class implements Serializable interface. Now its objects can be converted into stream. The main class implementation of is showed in the next code.
|
What is the ObjectOutputStream class?
|
The ObjectOutputStream class is used to write primitive data types, and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams.
Constructor: public ObjectOutputStream(OutputStream out) throws IOException {}
Description: It creates an ObjectOutputStream that writes to the specified OutputStream.
Important Methods
1) public final void writeObject(Object obj) throws IOException {} - It writes the specified object to the ObjectOutputStream.
2) public void flush() throws IOException {} - It flushes the current output stream.
3) public void close() throws IOException {} - It closes the current output stream.
|
What is the ObjectInputStream class?
|
An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.
Constructor: public ObjectInputStream(InputStream in) throws IOException {}
Description: It creates an ObjectInputStream that reads from the specified InputStream.
Important Methods
1) public final Object readObject() throws IOException, ClassNotFoundException{} - It reads an object from the input stream.
2) public void close() throws IOException {} - It closes ObjectInputStream.
|
Can you provide an Example of Java Serialization?
|
In this example, we are going to serialize the object of Student class from above code. The writeObject() method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named f.txt.
Persist.java
import java.io.*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
Output:
success
|
Can you provide an Example of Java Deserialization?
|
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object.
Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object.
Depersist.java
import java.io.*;
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
211 ravi
|
Can you give me the Java Serialization with Inheritance (IS-A Relationship)?
|
If a class implements Serializable interface then all its sub classes will also be serializable. Let's see the example given below:
SerializeISA.java
import java.io.Serializable;
class Person implements Serializable{
int id;
String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
class Student extends Person{
String course;
int fee;
public Student(int id, String name, String course, int fee) {
super(id,name);
this.course=course;
this.fee=fee;
}
}
public class SerializeISA
{
public static void main(String args[])
{
try{
//Creating the object
Student s1 =new Student(211,"ravi","Engineering",50000);
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name+" "+s.course+" "+s.fee);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
success
211 ravi Engineering 50000
The SerializeISA class has serialized the Student class object that extends the Person class which is Serializable. Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be.
|
Can you give me the Java Serialization with Aggregation (HAS-A Relationship)?
|
If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.
Address.java
class Address{
String addressLine,city,state;
public Address(String addressLine, String city, String state) {
this.addressLine=addressLine;
this.city=city;
this.state=state;
}
}
Student.java
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
Address address;//HAS-A
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
Since Address is not Serializable, you cannot serialize the instance of the Student class.
|
Can you provide the Java Serialization with the static data member?
|
If there is any static data member in a class, it will not be serialized because static is the part of class not object.
Employee.java
class Employee implements Serializable{
int id;
String name;
static String company="SSS IT Pvt Ltd";//it won't be serialized
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
|
What is Java Serialization with array or collection?
|
Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not serialiizable, serialization will be failed.
|
What is Externalizable in java?
|
The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface.
The Externalizable interface provides two methods:
-public void writeExternal(ObjectOutput out) throws IOException
-public void readExternal(ObjectInput in) throws IOException
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.