Hi,
Need example of fileoutputstream out.write to a file in Java.
Since I am getting "Red.java:6: unreported exception ava.io.FileNotFoundException; must be caught or declared to be thrown" error in my code.
Thanks in advance.
Hi,
Need example of fileoutputstream out.write to a file in Java.
Since I am getting "Red.java:6: unreported exception ava.io.FileNotFoundException; must be caught or declared to be thrown" error in my code.
Thanks in advance.
Output:Code:import java.io.*; public class WriteFile{ public static void main(String[] args) throws IOException{ File f=new File("textfile1.txt"); FileOutputStream fop=new FileOutputStream(f); if(f.exists()){ String str="This data is written through the program"; fop.write(str.getBytes()); fop.flush(); fop.close(); System.out.println("The data has been written"); } else System.out.println("This file is not exist"); } }
ExplanationCode:C:\ram>javac WriteFile.java C:\ram>java WriteFile The data has been written C:\ram>
Copy Bytes between FileInputStream and FileOutputStream
Code:import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
Here is a sample code:
Code:import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class WriteBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { int j; in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); while ((j = in.read()) != -1){ out.write(j); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } }
Bookmarks