FileOutputStream fos = new FileOutputStream ("data.txt'); DataOutputStream dos = new DataOutputStream (fos); // chainingSimilarly, while reading you need to chain the FileInputStream object to DataInputStream object and then call its read() methods to read data values from file. For example:
FileInputStream fis = new FileInputStream ("data.txt"); DataInputStream dis = newDataInputStream (fis); //chainingImplementation
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; public class DataInOutStream { public static void main(String[] args) { int productId = 1; String productName = "Laptop"; int quantity = 2; float price = 100000; int productId2 = 2; String productName2 = "Byke"; int quantity2 = 3; float price2 = 240000; try { FileOutputStream fos = new FileOutputStream("products.txt",true);//opening file in append mode DataOutputStream dos = new DataOutputStream(fos); //Write ist Record dos.writeInt(productId); dos.writeUTF(productName); dos.writeInt(quantity); dos.writeFloat(price); //write IInd Record dos.writeInt(productId2); dos.writeUTF(productName2); dos.writeInt(quantity2); dos.writeFloat(price2); dos.flush(); dos.close(); FileInputStream fis = new FileInputStream("products.txt"); DataInputStream dis = new DataInputStream(fis); // Reading Records from file try{ while(true) { productId = dis.readInt(); System.out.println("Id: " + productId); productName = dis.readUTF(); System.out.println("Name: " + productName); quantity = dis.readInt(); System.out.println("Quantity: " + quantity); price = dis.readFloat(); System.out.println("Price: " +price); } } catch(Exception ex){} dis.close(); } catch (IOException e) { e.printStackTrace(); } } }
OUTPUT Id: 1 Name: Laptop Quantity: 2 Price: 100000.0 Id: 2 Name: Byke Quantity: 3 Price: 240000.0
import java.io.*; public class readerWriterClasses { public static void main(String[] args) { try{ copyTextFile(); } catch(FileNotFoundException ex){ex.printStackTrace();} catch(IOException exp){exp.printStackTrace();} } static void copyTextFile()throws FileNotFoundException,IOException { File src=new File("real.txt"); FileReader read=new FileReader(src); FileWriter write=new FileWriter("realjava.txt"); int c; while(true) { c=read.read();//reading from file if(c==-1) break; write.write(c);// writing in file System.out.print((char)c); //print on Screen } read.close(); write.close(); System.out.println("\n File Copied......"); } }
File Copied