0% found this document useful (0 votes)
23 views2 pages

File Output Streams-2

output stream

Uploaded by

commonroom001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views2 pages

File Output Streams-2

output stream

Uploaded by

commonroom001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Programs based upon File Output Stream

/* PROGRAM 1: To write one character to a file. File name fs_1.java */


import java.io.FileOutputStream;
class fs_1
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("e:\\testout1.txt");
fout.write(65);
fout.close();
System.out.println("Success...");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output: Success...
Contents of testout1.txt file: A

Explanation:
1) Line import java.io.FileOutputStream; imports the
FileOutputStream class that will help us in writing data to
a file.
2) Line fout=new FileOutputStream("e:\\testout1.txt"); create
object fout of above class and open a new file testout1.txt
on drive E for writing data.
3) The method fout.write(65); will write character A to a file.
Note that 65 is the ASCII code for character A.
4) The method fout.close(); saves the file and close it.

5) Any error during opening file or writing process will be handled


by catch block written after try block.
/* PROGRAM 2: To write multiple characters/strings to a file.
Program file name fs_2.java */
import java.io.FileOutputStream;
class fs_2
{
public static void main(String args[])
{
try
{
FileOutputStream fout=new FileOutputStream("e:\\testout2.txt");
String s="Welcome to Java.";
String s1="\nJava is better than c and c++.";
String s2="\nJava is pure OOP Language.";
byte b[] = s.getBytes(); //converting string into bytes
byte b1[] = s1.getBytes(); //converting string into bytes
byte b2[] = s2.getBytes(); //converting string into bytes
fout.write(b);
fout.write(13); /* 13 is ASCII code for Enter or new line */
fout.write(b1);
fout.write(13);
fout.write(b2);
fout.close();
System.out.println("Success...");
}
catch(Exception e){ System.out.println(e);}
}
}
Output : Success...
Contents of testout2.txt file

Welcome to Java.
Java is better than c and c++.
Java is pure OOP Language.

***************** END OF FILE OUTPUT STREAM TOPIC *****************

You might also like