Text Files Example
 

  Introduction

JAVA
  Menu

  Sockets

  Text Files

CSS
  CSS tutorial

LINUX
  Commands

 
  

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();
	}
}