skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Saturday, October 6, 2012

File Parsing using Java IO

Posted by Raju Gupta at 1:02 AM – 0 comments
 
It is a simple attempt to parse a file using a simple logic. the program using Java I/O classes to read and write the text files.

import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;

class FileParse{

 public static void main(String arg[]){

  FileParse ssObj = new FileParse();
  try {
    BufferedReader in = new BufferedReader(new FileReader("SampleDataRead.txt"));  // input text file
    String inputLine;
    int tmp=0;

    while ((inputLine = in.readLine()) != null) {
   tmp++;
     ssObj.process(inputLine);
   System.out.println("Processing line "+tmp+"...");}

    in.close();
   } catch (IOException e) {
      System.out.println("There was a problem while reading: " + e);
   }
 }


 void process(String inputString){
  char charAry[] = inputString.toCharArray();// breaking into characters
  try {
   BufferedWriter out = new BufferedWriter(new FileWriter("SampleDataWrite.txt",true)); // true - appending
                        // Output file
   for(int i=0;i<charAry.length;i++) {
    if(charAry[i]==' ')
     out.write(charAry[i]+"#");  // # indicates End of word
    else{
     if(i<(charAry.length-1))
      out.write(charAry[i]+"$"); // $ indicated between every word
     else
      out.write(charAry[i]+"_|"); // _| indicates End of Line
     }
     }
   out.newLine();
   out.close();
  }catch(IOException e){
  System.out.println("There was a problem while writing:" + e);
  }
 }
}

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