Text Files Example

This example shows how to manipulate text files in Java. A file named “text.txt” is created and ten lines contaning the string “hello” are written to it. Then the function “readFile()” displays the content of the the created file to the screen


//TextFile.java
//manipulating text files
import java.io.*;
public class TextFile {
String fileName;
TextFile(String fn)
{
fileName = fn;
}
public void createFile()
{
}
public void writeToFile()
{
try{
PrintWriter out = new PrintWriter( new FileWriter( fileName ) );
for(int i = 0; i < 10; i++)
out.println("hello");
out.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
public void readFile()
{
System.out.println("Content of file: " + fileName);
try{
BufferedReader in = new BufferedReader(new FileReader( fileName ));
String line = "";
while((line = in.readLine()) != null)
System.out.println(line);
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
public static void main ( String[] args )
{
TextFile txtFile = new TextFile("text.txt");
txtFile.writeToFile();
txtFile.readFile();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s