java input output stream code example
Example 1: IO STREAMS in java
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Example 2: object input stream java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Dog implements Serializable {
String name;
String breed;
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog("Tyson", "Labrador");
try {
FileOutputStream fileOut = new FileOutputStream("file.txt");
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
objOut.writeObject(dog1);
FileInputStream fileIn = new FileInputStream("file.txt");
ObjectInputStream objIn = new ObjectInputStream(fileIn);
Dog newDog = (Dog) objIn.readObject();
System.out.println("Dog Name: " + newDog.name);
System.out.println("Dog Breed: " + newDog.breed);
objOut.close();
objIn.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}