skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, October 3, 2012

Read or Write data from or into text file

Posted by Admin at 6:25 PM – 0 comments
 
Reading the data from a text file or writing some data into a text file can be done easily using this Program

import java.io.*;


public class SimpleTest {

 public static void main(String[] args) {
  //Hard coded the stringbuffer data and the file path
  StringBuffer strBuff = new StringBuffer();
  strBuff.append("Java Program");
  String filePath = "/D://simple.txt"; 
  
  SimpleTest st = new SimpleTest();
  st.writeData(strBuff,filePath);
  String contents = st.readData(filePath);
  System.out.println("**********");
  System.out.println(contents);
  System.out.println("**********");
 }
 
 public void writeData(StringBuffer strBuff, String filePath){ 
  
  String strData = null;
  strData = strBuff+"";
  try{
   BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
   bw.write(strData);
   bw.flush();
   bw.close();
  }
  catch(FileNotFoundException e){
//    TODO Auto-generated catch block
   e.printStackTrace();
     }
  catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
 }
 
 public String readData(String filePath){
  
  String line = null;
  StringBuffer contents = new StringBuffer(); 
  try {
   BufferedReader br = new BufferedReader(new FileReader(filePath));
   while((line = br.readLine())!= null){
    contents.append(line);
    contents.append("\n");
   }
   br.close();
  } 
  catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (IOException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  return contents.toString();
 }
 
}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger