Wednesday, July 18, 2012

Reading and Writing Text files

Here is the file for writing text files. We tried to make it as generic as possible so it can be reused in a variety of contexts. One weakness of the class is that it is up to the user to call the closeFile method. A text file cannot be read or used if it is not closed

WriteFile.java


package com.spconger.www;

import java.io.*;

public class WriteFile {
 
 
 private String path;
 private PrintWriter writer;
 
 public WriteFile(String path) throws IOException{
  this.path=path;
  createFile();
 }
 
 private void createFile() throws IOException{
  
  
  FileWriter outFile = new FileWriter(path, true);
  writer = new PrintWriter(outFile);
  
 }
 public void addText(String content){
  
  writer.println(content);
 
 }
 
 public void closeFile(){
  writer.close();
 }
 

}


Here is the ReadFile.Java

package com.spconger.www;

import java.io.*;

public class ReadFile {
 
 private String path;
 
 public ReadFile(String path){
  this.path=path;
 }
 
 public String getText() throws FileNotFoundException ,IOException{
  String content="";
  FileInputStream fstream = new FileInputStream(path);
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  while ((strLine=br.readLine()) != null){
   content += (strLine + "\n");
  }
  
  return content;
 }

}


Here is the Program.java where we test our classes


package com.spconger.www;

import java.io.IOException;



public class Program {

 /**
  * @param args
  * 
  */
 public static void main(String[] args) {
  
   try {
    WriteFile write = new WriteFile("email.txt");
    write.addText("Steve" + ", steven.conger@seattlecolleges.edu");
    write.addText("George" + ", george@gmail.com");
    write.closeFile();
    
    ReadFile read = new ReadFile("email.txt");
    System.out.println(read.getText());
    
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   
  
   
  }
  

 }


No comments:

Post a Comment