Wednesday, February 1, 2012

Creating .txt file and writing text to it in Character Stream

// Usage of FileWriter (Unicode format)

import java.io.*;
class FileWriterDemo
{
public static void main(String args[]) throws Exception
{
String source = "Welcome to the FileWriter Demo\n" + " Thanks for visiting\n" + " visit again.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);

FileWriter f0 = new FileWriter("file2.txt"); //stores the odd characters in file2.txt
for (int i=0; i < buffer.length; i += 2)
{
f0.write(buffer[i]);
}
f0.close();

FileWriter f1 = new FileWriter("file3.txt"); //stores all characters in file3.txt
f1.write(buffer);
f1.close();

FileWriter f2 = new FileWriter("file4.txt"); //stores the specifies index characters in file4.txt
f2.write(buffer,0,5); //stores 0 to 4th index character
f2.close();
}
}

Output:

Creates a three files file2.txt, file3.txt, file4.txt in the current folder path

No comments:

Post a Comment