File and FileWriter

Hello,
I wanna create a new file if there is no, or append the file if there already is one..
I wanna do this with FileWriter so I can then change the Stream o which I write the rest of the text...
Is this possible and how?
Regards, Anze Vodovnik

File file = new File("output", "log.log");
PrintWriter printwriter = new PrintWriter(new FileWriter(file.getAbsolutePath() ), true);
printwriter.println("what you want in the file");
printwriter.close();output is the directory, log.log is the filename. If the file doesnt excist it will be created. If the file does exsist it will be appended to the excisting file.
You can replace printwriter with any writer you like, thats just for the example.

Similar Messages

  • Questions about Using Vector To File And JTable

    hi all
    I want to write all data from Vector To File and read from file To Vector
    And I want To show all data from vector to JTable
    Note: I'm using the JBuilder Compiler
    This is Class A that my datamember  And Methods in it
    import java.io.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public  class A implements Serializable {
      int no;
      String name;
      int age;
      public void setA (int n,String na,int a)
        no=n;
        name=na;
        age=a;
      public void set_no(int n)
        no = n;
      public void set_age(int a)
        age = a;
        public int getage ()
        return age;
      public void setName(String a)
        name  = a;
      public String getname ()
        return name;
      public int getno ()
        return no;
    This is The Frame That the JTextFeild And JButtons & JTable in it
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Frame1 extends JFrame {
    /* Vector v = new Vector ();
      public int i=0;*/
      A a = new A();
      XYLayout xYLayout1 = new XYLayout();
      JTextField txtno = new JTextField();
      JTextField txtname = new JTextField();
      JTextField txtage = new JTextField();
      JButton add = new JButton();
      JButton search = new JButton();
      /*JTable jTable1 = new JTable();
      TableModel tableModel1 = new MyTableModel(*/
                TableModel dataModel = new AbstractTableModel() {
              public int getColumnCount() { return 2; }
              public int getRowCount() { return 2;}
              public Object getValueAt(int row, int col) { return new A(); }
          JTable table = new JTable(dataModel);
          JScrollPane scrollpane = new JScrollPane(table);
      TitledBorder titledBorder1;
      TitledBorder titledBorder2;
      ObjectInputStream in;
      ObjectOutputStream out;
      JButton read = new JButton();
      public Frame1() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        titledBorder1 = new TitledBorder(BorderFactory.createEmptyBorder(),"");
        titledBorder2 = new TitledBorder("");
        this.getContentPane().setLayout(xYLayout1);
        add.setBorder(BorderFactory.createRaisedBevelBorder());
        add.setNextFocusableComponent(txtno);
        add.setMnemonic('0');
        add.setText("Add");
        add.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            add_actionPerformed(e);
        add.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            add_actionPerformed(e);
        search.setFocusPainted(false);
        search.setText("Search");
        search.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            search_actionPerformed(e);
        xYLayout1.setWidth(411);
        xYLayout1.setHeight(350);
        read.setText("Read");
        read.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            read_actionPerformed(e);
        this.getContentPane().add(txtno, new XYConstraints(43, 35, 115, 23));
        this.getContentPane().add(txtname,  new XYConstraints(44, 67, 114, 22));
        this.getContentPane().add(txtage,      new XYConstraints(44, 97, 115, 23));
        this.getContentPane().add(add,      new XYConstraints(60, 184, 97, 26));
        this.getContentPane().add(search,  new XYConstraints(167, 185, 88, 24));
        this.getContentPane().add(table,   new XYConstraints(187, 24, 205, 119));
        this.getContentPane().add(read,   new XYConstraints(265, 185, 75, 24));
        this.setSize(450,250);
        table.setGridColor(new Color(0,0,255));
      void add_actionPerformed(ActionEvent e)
        a.set_no(Integer.parseInt(txtno.getText()));
        a.setName(txtname.getText());
        a.set_age(Integer.parseInt(txtage.getText()));
        fileOutput();
        txtno.setText(null);
        txtname.setText(null);
        txtage.setText(null);
        try
          out.writeObject(a);
          out.close();
        }catch (Exception excep){};
    /*  try
           add.setDefaultCapable(true);
          v.addElement(new A());
         ((A)v.elementAt(i)).setA(Integer.parseInt(txtno.getText()),txtname.getText(),Integer.parseInt(txtage.getText()));
        JOptionPane.showMessageDialog(null,"The Record is Added");
        txtno.setText(null);
        txtname.setText(null);
        txtage.setText(null);
        i++;
      }catch (Exception excep){};*/
      void search_actionPerformed(ActionEvent e) {
        int n = Integer.parseInt(JOptionPane.showInputDialog("Enter No:"));
        for (int i=0;i<v.size();i++)
          if (((A)v.elementAt(i)).getno()==n)
            txtno.setText(Integer.toString(((A)v.elementAt(i)).getno()));
            txtname.setText(((A)v.elementAt(i)).getname() );
            txtage.setText(Integer.toString(((A)v.elementAt(i)).getage()));
      public void fileOutput()
        try
          out = new ObjectOutputStream(new FileOutputStream("c:\\UserData.txt",true));
        }catch(Exception excep){};
      public void fileInput()
        try
          in = new ObjectInputStream(new FileInputStream("c:\\UserData.txt"));
        }catch(Exception excep){};
      void read_actionPerformed(ActionEvent e) {
      fileInput();
        try
          a = (A)in.readObject();
          txtno.setText(Integer.toString(a.getno()));
          txtname.setText(a.getname());
          txtage.setText(Integer.toString(a.getage()));
        }catch (Exception excep){};
    }

    //program which copies string data between vector and file
    import java.util.*;
    import java.io.*;
    class Util
    private Vector v;
    private FileReader filereader;
    private FileWriter filewriter;
    Util(String data[])throws Exception
      v=new Vector();
      for(String o:data)
        v.add(o);
    public void listData()throws Exception
      int size=v.size();
      for(int i=0;i<size;i++)
       System.out.println(v.get(i));
    public void copyToFile(String data,String fname)throws Exception
      filewriter =new FileWriter(fname);
      filewriter.write(data);
      filewriter.flush();
      System.out.println("Vector content copied into file..."+fname);
    public void copyFromFile(String fname)throws Exception
      filereader=new FileReader(fname);
      char fcont[]=new char[(int)new File(fname).length()];
      filereader.read(fcont,0,fcont.length);
      String temp=new String(fcont); 
      String fdata[]=temp.substring(1,temp.length()-1).split(",");
      for(String s:fdata)
        v.add(s.trim()); 
      System.out.println("File content copied into Vector...");
    public String getData()throws Exception
       return(v.toString());
    class TestUtil
    public static void main(String a[])throws Exception
      String arr[]={"siva","rama","krishna"};
      Util util=new Util(arr);
      System.out.println("before copy from file...");
      util.listData();
      String fname=System.getProperty("user.home")+"\\"+"vecdata";
      util.copyToFile(util.getData(),fname);
      util.copyFromFile(fname);
      System.out.println("after copy from file...");
      util.listData();
    }

  • Read multiple files and save all into one output file(AGAIN)

    Hi, guys
    I need your help for reading data from multiple files and save the results into one output file. When files are selected from file chooser, my program read the data line by line , do some calculations and save the result into the output. I made an array to store input files and it seems to be working fine, but when it comes to SaveFile() function, issues NullPointException message.
    public class FileReduction1 extends JFrame implements ActionListener
       // GUI definition and layout
        /* ACTION PERFORMED */
        public void actionPerformed(ActionEvent event) {
            if (event.getActionCommand().equals("Open File")) getFileName();
        /* OPEN THE FILE */
        private void getFileName() {
            // Display file dialog so user can select file to open
         JFileChooser fileChooser = new JFileChooser();
         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(true);
         int result = fileChooser.showOpenDialog(this);
         // If cancel button selected return
         if (result == JFileChooser.CANCEL_OPTION) return;
            if (result == JFileChooser.APPROVE_OPTION)
             files = fileChooser.getSelectedFiles();
                textArea.setText("");
                if(files.length>0)
                    filelist="";
                    System.out.println("files length"+files.length);
                    for(int i=0;i<files.length;i++)
                         System.out.println(files.getName());
    filelist+=files[i].getName()+" ,";
    if (checkFileName(files[i]) )
    openButton.setEnabled(true);
    readButton.setEnabled(true);
    textArea.append("file "+files[i].getName()+"is a proper file"+"\n");
    readFile(files[i]);
    textfield.setText(filelist);
    else{JOptionPane.showMessageDialog(this,"Please select file(s)",
                    "Error 5: ",JOptionPane.ERROR_MESSAGE); }
         // Obtain selected file
    /* READ FILE */
    private void readFile(File fileName_in) {
    // Disable read button
    readButton.setEnabled(false);
    // Dimension data structure
         getNumberOfLines(fileName_in);
         data = new String[numLines][4];
         // Read file
         readTheFile(fileName_in);
         // Rnable open button
         openButton.setEnabled(true);
    /* GET NUMBER OF LINES */
    /* Get number of lines in file and prepare data structure. */
    private void getNumberOfLines(File fileName_in) {
    int counter = 0;
         // Open the file
         openFile(fileName_in);
         // Loop through file incrementing counter
         try {
         String line = fileInput.readLine();
         while (line != null) {
         counter++;
              System.out.println("(" + counter + ") " + line);
    line = fileInput.readLine();
         numLines = counter;
    closeFile(fileName_in);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error reading File",
                   "Error 5: ",JOptionPane.ERROR_MESSAGE);
         closeFile(fileName_in);
         System.exit(1);
    /* READ FILE */
    private void readTheFile(File fileName_in)
    // Open the file
    //int row=0;
    int col=0;
    openFile(fileName_in);
    System.out.println("Read the file");
    // Loop through file incrementing counter
    try
    String line = fileInput.readLine();
    while (line != null)
    boolean containsDoubles = false;
    double temp;
    String[] lineParts = line.split("\t");
    try
    for (col=0;col<lineParts.length;col++)
    temp=Double.parseDouble(lineParts[col]);
    data[row][col] = lineParts[col];
    containsDoubles = true;
    System.out.print("data["+row+"]["+col+"]="+lineParts[col]+" ");
    } catch (Exception e) {row=0; col=0; temp=0.0;}
    if (containsDoubles){ row++;}
    System.out.println();
    line = fileInput.readLine();
    catch(IOException ioException)
    JOptionPane.showMessageDialog(this,"Error reading File", "Error 5: ",JOptionPane.ERROR_MESSAGE);
    closeFile(fileName_in);
    System.exit(1);
    //System.out.println("length"+data.length);
    closeFile(fileName_in);
    process(fileName_in);
    /* CHECK FILE NAME */
    /* Return flase if selected file is a directory, access is denied or is
    not a file name. */
    private boolean checkFileName(File fileName_in) {
         if (fileName_in.exists()) {
         if (fileName_in.canRead()) {
              if (fileName_in.isFile()) return(true);
              else JOptionPane.showMessageDialog(null,
                        "ERROR 3: File is a directory");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 2: Access denied");
         else JOptionPane.showMessageDialog(null,
                        "ERROR 1: No such file!");
         // Return
         return(false);
    /* OPEN FILE */
    private void openFile(File fileName_in) {
         try {
         // Open file
         FileReader file = new FileReader(fileName_in);
         fileInput = new BufferedReader(file);
         catch(IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
         textArea.append("OPEN FILE\n---------\n");
         textArea.append(fileName_in.getPath());
         textArea.append("\n");
         //System.out.println("File opened successfully");
    /* CLOSE FILE */
    private void closeFile(File fileName_in) {
    if (fileInput != null) {
         try {
              fileInput.close();
         catch (IOException ioException) {
         JOptionPane.showMessageDialog(this,"Error Opening File",
                   "Error 4: ",JOptionPane.ERROR_MESSAGE);
    System.out.println("File closed");
    private void process(File fileName_in) {
    //getNumberOfLines();
         //data = new String[numLines][3];
         // Read file
    double temp,temp1;
         //readTheFile();
    //System.out.println("row:"+row);
    //int number=data.length;
    //System.out.println(number);
    for (int i=0; i<row; i++)
    temp=Double.parseDouble(data[i][1]);
    sumx+=temp;
    temp1=Double.parseDouble(data[i][3]);
    sumy+=temp1;
    multixy+=(temp*temp1);
    square_x_sum+=(temp*temp);
    square_y_sum+=(temp1*temp1);
    //System.out.println("Sum(x)="+sumx);
    double tempup=(row*multixy)-(sumx*sumy);
    double tempdown=(row*square_x_sum)-(sumx*sumx);
    slope=tempup/tempdown;
    double tempbup=sumy-(slope*sumx);
    intb=tempbup/row;
    double tempside=(row*square_y_sum)-(sumy*sumy);
    double cordown=Math.sqrt(tempdown*tempside);
    corr=tempup/cordown;
    r_sqrt=corr*corr;
         textArea.append("Data for file"+ fileName_in.getName()+" have been processed successfully.");
         textArea.append("\n");
         textArea.append("Please enter output file name including extension.");
    System.out.println("number"+row);
    System.out.println("slope(m)="+slope);
    System.out.println("intecept b="+intb);
    System.out.println("correlation="+corr);
    System.out.println("correlation="+r_sqrt);
    saveFile();
    private void saveFile()
    textArea.append("SAVE FILE\n---------\n");
    if (openFile1())
         try {
              outputToFile();
    catch (IOException ioException) {
              JOptionPane.showMessageDialog(this,"Error Writing to File",
                   "Error",JOptionPane.ERROR_MESSAGE);
    private boolean openFile1 ()
         // search for the file path
    StringBuffer stringpath;
    title=textfield1.getText().trim();
    int temp=fileName_in.getName().length();
    int temp_path=fileName_in.getPath().length();
    int startd=(temp_path-temp);
    stringpath=new StringBuffer(fileName_in.getPath());
    stringpath.delete(startd, temp_path+1);
    //System.out.println("file-path="+temp_path);
    //System.out.println("length-file="+temp);
    path=stringpath.toString();
    fileName_out = new File(path, title);
    //System.out.println(file_out.getName());
    if (fileName_out==null || fileName_out.getName().equals(""))
         JOptionPane.showMessageDialog(this,"Invalid File name",
                   "Invalid File name",JOptionPane.ERROR_MESSAGE);
         return(false);
         else
    try
    boolean created = fileName_out.createNewFile();
    if(created)
    fileOutput = new PrintWriter(new FileWriter(fileName_out));
    fileOutput.println("File Name"+"\t"+"Slope(m)"+"\t"+"y-intercept(b)"+"\t"+"Coefficient(r)"+"\t"+"Correlation(R-Squared)");
    return(true);
    else
    fileOutput = new PrintWriter(new FileWriter(fileName_out,true));
    return(true);
    catch (IOException exc)
    JOptionPane.showMessageDialog(this,"Please enter the file name","Error",JOptionPane.ERROR_MESSAGE);
    return(false);
    private void outputToFile() throws IOException
    // Initial output
         textArea.append("File name = " + fileName_out + "\n");
         // Test if data exists
         if (data != null)
         fileOutput.println(fileName_in.getName() +"\t"+ slope+"\t"+intb+"\t"+corr+"\t"+r_sqrt);
    textArea.append("File output complete\n\n");
         else
    textArea.append("No data\n\n");
         // End by closing file
    initialcomp();
         fileOutput.close();
    private void initialcomp()
    slope=0.0;
    intb=0.0;
    corr=0.0;
    r_sqrt=0.0;
    sumx=0.0; sumy=0.0; multixy=0.0; square_x_sum=0.0; square_y_sum=0.0;
    for(int i=0;i<data.length;i++)
    for(int j=0;j<data[i].length;j++)
    data[i][j]=null;
    /* MAIN METHOD */
    public static void main(String[] args) throws IOException
         // Create instance of class FileChooser
         FileReduction1 newFile = new FileReduction1("File Reduction Program");
         // Make window vissible
         newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         newFile.setSize(500,400);
    newFile.setVisible(true);
    Sorry about the long lines.
    As you can see, all input files saved in array called files, however when OpenFile1() function is called, it take input (fileName_in) as a single file not an array. I'm assuming this causes the exception.
    When there's muptiple inputs, program should take each file from getFileName() to outputToFile() sequentially.
    Does anybody have an idea to solve this?
    Thanks a lot!!

    you naming convention is confussing. you should follows Java naming convention..you have a getXXX but decalred the return type as "void"...get usully means to return something...
    your code is doing too much..and hard to follows..
    1. get the selected files
    for each selected file
    process the file and return the result
    write out the result.
    /** close the precious resource */
    public void closeResource(Reader in){
        if (in != null){
            try{ in.close(); }
            catch (Exception e){}
    /** get the total number of line in a file */
    public int getLineCount(File file) throws IOException{
        BufferedReader in = null;
        int lineCount = 0;
        try{
            in = new BufferedReader(new FileReader(file));
            while ((in.readLine() != null)
                lineCount++;
            return lineCount;
        finally{ closeResource (in);  }
    /** read the file */
    public void processFile(File inFile, File outFile) throws IOException{
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try{
            in = new BufferedReader(new FileReader(inFile));
            String line = null;
            while ((in.readLine() != null){
                .. do something with the line
                result.append(....);
            writeToFile(outFile, result.toString());
        finally{ closeResource (in);  }
    public void writeToFile(File outFile, String result) throws IOException{
        PrintWriter out = null;
        try{
            out = new PrintWriter(new FileWriter(outFile, true));  // true for appending to the end of the file
            out.println(result);
        finally{  if (out != null){ try{ out.close(); } catch (Exception e){} }  }
    }

  • Writing out to file - and it seems to overwrite data

    I have written a program that reads in a file and then writes out XML. It works fine with small files but with files that are 1,310 kb it, seems to overwrite itself and i end up with a file that is missing its begining and middle pieces. I suspect that I am blowing out some buffer and a java component is reseting itself and overwriting the file, but i am scratching my head. Code below, please excuse the unformatted nature of the code.
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.*;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    public class dl414image {
    public static String all = "";
    public static String fname = "";
    public static String lname = "";
    public static String mname = "";
    public static boolean aflag = false;
    public static boolean endofrec = false;
    public static boolean bflag = false;
    public static boolean cflag = false;
    public static boolean dflag = false;
    public static String xmldl;
    public static String xmlreq;
    public static String xml_issue_date;
    public static String xml_first_name;
    public static String xml_middle_name;
    public static String xml_last_name;
    public static String xml_dmvinfo;
    public static String xmlbday;
    public static String xmlsex;
    public static String xmlheight;
    public static String xmlweight;
    public static String xmleyecolor;
    public static String xmlhaircolor;
    public static String xml_licenseclass;
    public static String xml_licenseclassname;
    public static String xml_licenseissuedate;
    public static String xml_licenseexpiresdate;
    public static String dlstart = "<dlnumber>";
    public static String dlend = "</dlnumber>";
    public static String xmlreqstart = "<requestor_code>";
    public static String xmlreqend = "</requestor_code>";     
    public static String issue_date_start = "<issue_date>";
    public static String xml_issue_date_end = "</issue_date>";
    public static int count = 0;
    public static List<String> xml_abstractline = new ArrayList<String>();
    public static List<String> xml_cline = new ArrayList<String>();
    public static List<String> xml_dline = new ArrayList<String>();
    public static List<String> xml_acontinuedline = new ArrayList<String>();
    public static String dlold; // holds the previous DL number
    public static final String HEX_EXP = "[\\xFF]";
    public static final String CDATASTART = " <![CDATA[";
    public static final String CDATAEND = "]]>";
    public static String xmlfobates = "";
    public static String xmltypeappdate = "";
    public static String xml_licenseext;
    public static String xml_licenserestrict;
    public static String xml_licensedup;
    public static String xml_licenseheld;
    public static String xml_licenseseq;
    public static List<String> xml_abstract_item = new ArrayList<String>();
    public static List<String> xml_abstract_violationdate = new ArrayList<String>();
    public static List<String> xml_abstract_convictdate = new ArrayList<String>();
    public static List<String> xml_abstract_sectviolated = new ArrayList<String>();
    public static List<String> xml_abstract_statute = new ArrayList<String>();
    public static List<String> xml_abstract_file_number = new ArrayList<String>();
    public static List<String> xml_abstract_location_or_arn = new ArrayList<String>();
    public static List<String> xml_abstract_vehicle_license = new ArrayList<String>();
    public static final String ABST = "ABST";
    public static List<String> xml_reqNameAddress = new ArrayList<String>();
         /**<p>
         * This code reads in a file line by line
         * with BufferedReader and processes each
         * line.
         * @author Toren Valone
         public static void main(String[] args) {
              read("U:\\dlbig.txt"); //read this file
    //     convenience method to encapsulate
    //     the work of reading data.
         public static void read(String fileName) {
              xmlwriter("<?xml version=\"1.0\"?>");
              xmlwriter("<?xml-stylesheet type=\"text/xsl\" href=\"dl414.xsl\"?>" );
              xmlwriter("<dl_records>"); //write base element start tag
         try {
         BufferedReader in = new BufferedReader(
         new FileReader(fileName));
         String line;
         while ((line = in.readLine()) != null) {
              String cleanline = stripNonValidXMLCharacters(line);
         //our own method to do something
         handle(cleanline);
         //count each line
         count++;
         in.close();
         //show total at the end of file
         log("Lines read: " + count);
         } catch (IOException e) {
         log(e.getMessage());
         dlxmlwriter(); //final write for process
              xmlwriter("</dl_records>"); //write base element end tag
    //     does the work on every line as it is
    //     read in by our read method
         private static void handle(String line){
              if(line.length()> 0) {
              char fbyte = line.charAt(0);
              if(fbyte == 'A') {
              //just grab the very first dl
              if(count == 0) {
              dlold = line.substring(3,11);
              aflag = true;
              cflag = false;
              dflag = false;
              if(dlold.equalsIgnoreCase(line.substring(3,11))) {
              } else {
                   dlxmlwriter();
              //create Drivers License XML
                   xmldl = dlstart + line.substring(3,11) + dlend;
                   //grab f.o bates no only if its there otherwise write empty xml
              xmlfobates = "<fobates>" + line.substring(12,19) + "</fobates>";
              //grab type app and date
              xmltypeappdate = "<typeappdate>" + line.substring(20,28) + "</typeappdate>";
                   //Create Requestor code XML
              xmlreq = xmlreqstart + line.substring(51,56) + xmlreqend;
              //Create issue date XML
              xml_issue_date = issue_date_start + line.substring(57,63) + xml_issue_date_end;
              // clear name values, for now too stupid to figure out
              fname = "";
              mname = "";
              lname = "";     
              //Pulls the whole name string and sends it to namer function
              //to break up
              String name = line.substring(72);
              namer(name);
              //Create a string array and call get_Names which returns a
              //string array
              xml_first_name = "<first_name>" + fname + "</first_name>";
              xml_middle_name = "<middle_name>" + mname + "</middle_name>";
              xml_last_name = "<last_name>" + lname + "</last_name>";
                   //store Dl for comparison
                   store_old_dl(line);
              //Accent a and a length of 59 or 102 contains
              //the dmv info line
              if((fbyte == '?')& (line.length() == 59)){
                   String cleandmvinfo = regexReplacer(line.substring(38,58),"//","");
                   xml_dmvinfo = "<dmv_info_line>" + cleandmvinfo + "</dmv_info_line>";
              //Line length of 33 Birthdate, Sex, Height, Weight
              //Eye color hair color
              if ((line.length() == 33 ) & (aflag == true)) {
                   xmlbday = "<birth_date>" + line.substring(3, 9) + "</birth_date>";
                   xmlsex = "<sex>" + line.substring(11,12) + "</sex>";
                   xmlheight = "<height>" + line.substring(14,17) + "</height>";
                   xmlweight = "<weight>" + line.substring(18,21) + "</weight>";
                   xmleyecolor = "<eye_color>" + line.substring(22,27) + "</eye_color>";
                   xmlhaircolor = "<hair_color>" + line.substring(28,line.length()) + "</hair_color>";
    //Line length of 35 Birthdate, Sex, Height, Weight
              //Eye color hair color
              if ((line.length() == 31     ) & (aflag == true)) {
                   xmlbday = "<birth_date>" + line.substring(3, 9) + "</birth_date>";
                   xmlsex = "<sex>" + line.substring(11,12) + "</sex>";
                   xmlheight = "<height>" + line.substring(14,17) + "</height>";
                   xmlweight = "<weight>" + line.substring(18,21) + "</weight>";
                   xmleyecolor = "<eye_color>" + line.substring(22,27) + "</eye_color>";
                   xmlhaircolor = "<hair_color>" + line.substring(28,31) + "</hair_color>";
    // Line length of 56 Birthdate, Sex, Height, Weight
              //Eye color hair color for Annual reports
              if ((line.length() == 56     ) & (aflag == true)) {
                   xmlbday = "<birth_date>" + line.substring(3, 9) + "</birth_date>";
                   xmlsex = "<sex>" + line.substring(11,12) + "</sex>";
                   xmlheight = "<height>" + line.substring(14,17) + "</height>";
                   xmlweight = "<weight>" + line.substring(18,21) + "</weight>";
                   xmleyecolor = "<eye_color>" + line.substring(22,27) + "</eye_color>";
                   xmlhaircolor = "<hair_color>" + line.substring(28,31) + "</hair_color>";
              //If the line has an accent a and a length of 6
              if ((fbyte == '?')& (line.length() == 6)) {
              xml_licenseclass = "<license_class>" + line.substring(5,6) + "</license_class>";
              if ((fbyte == '?')& (line.length() == 8)) {
                   String cleanlc = regexReplacer(line.substring(4,8),"&","&");
                   xml_licenseclass = "<license_class>" + cleanlc + "</license_class>";
              if((line.length() == 61) & aflag==true) {
                   xml_licenseclassname = "<license_class_name>" + line.substring(3,9) + "</license_class_name>";
                   xml_licenseissuedate = "<license_issue_date>" + line.substring(9,16) + "</license_issue_date>";
                   xml_licenseexpiresdate = "<license_expires_date>" + line.substring(16,23) + "</license_expires_date>";
                   xml_licenseext = "<license_ext>" + line.substring(23,26) + "</license_ext>";
                   xml_licenserestrict = "<license_restrict>" + line.substring(26,37) + "</license_restrict>";          
                   xml_licensedup = "<license_dup>" + line.substring(38,43) + "</license_dup>";
                   xml_licenseheld = "<license_held>" + line.substring(44,44) + "</license_held>";
                   xml_licenseseq = "<license_seq>" + line.substring(57,61) + "</license_seq>";
              if(fbyte == 'B') {
                   bflag = true;
                   aflag = false; //ok got the a now turn switch off
                   String cleanabstract = regexReplacer(line.substring(1,line.length()),HEX_EXP,"");
                   cleanabstract = regexReplacer(cleanabstract,"&","&");
                   cleanabstract = regexReplacer(cleanabstract,"&","&apos;");
              if(cleanabstract.substring(3, 7).equalsIgnoreCase("ABST")){
                   if(cleanabstract.length() == 107) {               
                        xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                   xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                   xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                   xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                   xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,46) + "</abs_statute>");
                   xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                   xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                   xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,107) + "</abs_vehicle_license>");               
                   if(cleanabstract.length() > 80 & cleanabstract.length() < 107) {               
                        xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                   xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                   xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                   xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                   xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,51) + "</abs_statute>");
                   xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                   xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,cleanabstract.length()) + "</abs_location_or_arn>");
                   if(cleanabstract.length() < 80) {
                   System.out.println("****Change your assumtions about length*********");     
                        xml_abstractline.add("<abstract>" + cleanabstract + "</abstract>");
              if(cleanabstract.substring(3, 6).equalsIgnoreCase("ACC")){
                   if(cleanabstract.length() < 107) {
                        System.out.println("Acc looks like!!!" + cleanabstract);
                        System.out.println("Acc length=" + cleanabstract.length());
                   if(cleanabstract.length() > 102) {               
                             xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,cleanabstract.length()) + "</abs_vehicle_license>");               
                   if((cleanabstract.length() > 77 ) & cleanabstract.length() < 102) {               
                             xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,cleanabstract.length()) + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
              if((fbyte == ' ') & (bflag == true)) {
                   String cleanabstract = regexReplacer(line.substring(1,line.length()),HEX_EXP,".");
                   cleanabstract = regexReplacer(cleanabstract,"&","&");
                   cleanabstract = regexReplacer(cleanabstract,"'","&apos;");
                   if(cleanabstract.substring(3, 7).equalsIgnoreCase("ABST")){
                             if(cleanabstract.length() == 107) {               
                                  xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                             xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                             xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                             xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                             xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,51) + "</abs_statute>");
                             xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                             xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                             xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,107) + "</abs_vehicle_license>");               
                             if(cleanabstract.length() > 93 & cleanabstract.length() < 107) {               
                                  xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,8) + "</abstract_item>");
                             xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                             xml_abstract_convictdate.add("<abs_convict_date>" + cleanabstract.substring(15,21) + "</abs_convict_date>");
                             xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                             xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,51) + "</abs_statute>");
                             xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                             xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,cleanabstract.length()) + "</abs_location_or_arn>");
                             xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   if(cleanabstract.substring(3, 6).equalsIgnoreCase("ACC")){
                             if(cleanabstract.length() > 102) {               
                                       xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                                  xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                                  xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                                  xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                                  xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                                  xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,79) + "</abs_file_number>");
                                  xml_abstract_location_or_arn.add("<abs_location_or_arn>" + cleanabstract.substring(79,99) + "</abs_location_or_arn>");
                                  xml_abstract_vehicle_license.add("<abs_vehicle_license>" + cleanabstract.substring(100,cleanabstract.length()) + "</abs_vehicle_license>");               
                             if((cleanabstract.length() > 77 ) & cleanabstract.length() < 102) {               
                                       xml_abstract_item.add("<abstract_item>" + cleanabstract.substring(3,6) + "</abstract_item>");
                                  xml_abstract_violationdate.add("<abs_violation_date>" + cleanabstract.substring(8,14) + "</abs_violation_date>");
                                  xml_abstract_convictdate.add("<abs_convict_date>" + " " + "</abs_convict_date>");
                                  xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                                  xml_abstract_statute.add("<abs_statute>" + " " + "</abs_statute>");
                                  xml_abstract_file_number.add("<abs_file_number>" + cleanabstract.substring(67     ,cleanabstract.length()) + "</abs_file_number>");
                                  xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                                  xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   if(cleanabstract.length() == 46) {
                   if(cleanabstract.substring(22, 25).equalsIgnoreCase("CDL") & cleanabstract.length() == 46) {
                   xml_abstract_item.add("<abstract_item>" + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,43) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + cleanabstract.substring(42,cleanabstract.length()) + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   if(cleanabstract.length()> 39 & cleanabstract.length() < 43     ) {
                   if(cleanabstract.substring(22, 25).equalsIgnoreCase("DMV")) {
                        System.out.println("DMV length=" + cleanabstract.length());
                        xml_abstract_item.add("<abstract_item>" + "</abstract_item>");
                        xml_abstract_violationdate.add("<abs_violation_date>" + "</abs_violation_date>");
                        xml_abstract_convictdate.add("<abs_convict_date>" + "</abs_convict_date>");
                        xml_abstract_sectviolated.add("<abs_section_violated>" + cleanabstract.substring(22,cleanabstract.length()) + "</abs_section_violated>");
                        xml_abstract_statute.add("<abs_statute>" + "</abs_statute>");
                        xml_abstract_file_number.add("<abs_file_number>" + "</abs_file_number>");
                        xml_abstract_location_or_arn.add("<abs_location_or_arn>" + "</abs_location_or_arn>");
                        xml_abstract_vehicle_license.add("<abs_vehicle_license>" + "</abs_vehicle_license>");               
                   xml_abstractline.add("<abstract>" + cleanabstract + "</abstract>");
              if(fbyte == 'C') {
                   //turn b flag off
                   aflag = false;
                   bflag = false;
                   cflag = true;
                   String cleancomment = regexReplacer(line.substring(1,line.length()),HEX_EXP,"");     
                   cleancomment = regexReplacer(cleancomment,"&","&");
                   cleancomment = regexReplacer(cleancomment,"'","&apos;");
                   xml_cline.add("<comment_line>" + cleancomment.substring(1,63) + "</comment_line>");
                   xml_reqNameAddress.add("<requestor_name_or_address>" + cleancomment.substring(63,cleancomment.length()) + "</requestor_name_or_address>");
                   System.out.println("In C code dl=" + xmldl + "aflag=" + aflag +"bflag=" + bflag + "cflag=" + cflag);           
              if((fbyte == ' ') & (cflag == true)){
                   String cleancomment = regexReplacer(line.substring(1,line.length()),HEX_EXP,"");     
                   cleancomment = regexReplacer(cleancomment,"&","&");
                   if(cleancomment.length() > 63) {
              xml_reqNameAddress.add("<requestor_name_or_address>" + cleancomment.substring(63,cleancomment.length()) + "</requestor_name_or_address>");
              xml_cline.add("<comment_line>" + cleancomment.substring(1, 63) + "</comment_line>");
                   } else {
                        xml_cline.add("<comment_line>" + cleancomment.substring(1, cleancomment.length()) + "</comment_line>");
              if(fbyte == 'D') {
                   xml_dline.add("<action>" + line.substring(1, line.length()) + "</action>");
                   dflag = true;
                   cflag = false;
                   System.out.println("In d code dl=" + xmldl + "aflag=" + aflag +"bflag=" + bflag + "cflag=" + cflag + "dflag=" + dflag);
              } // ends d if
              //If D line sets it to true then this will never run
              if((fbyte == ' ') & (dflag == true)) {
                   xml_dline.add("<action>" + line.substring(1, line.length()) + "</action>");
              }     //end if line length greater than zero
         }// ends handle     
         public static void store_old_dl(String line) {
              dlold = line.substring(3,11);
         public static void dlxmlwriter(){
    xmlwriter("<dl_record>");
         xmlwriter(xmldl);
         xmlwriter(xmlfobates);
         xmlwriter(xmltypeappdate);
         xmlwriter(xmlreq);
         xmlwriter(xml_issue_date);
         xmlwriter(xml_first_name);
         xmlwriter(xml_middle_name);
         xmlwriter(xml_last_name);
         xmlwriter(xml_dmvinfo);
         xmlwriter(xmlbday);
         xmlwriter(xmlsex);
         xmlwriter(xmlheight);     
         xmlwriter(xmlweight);
         xmlwriter(xmleyecolor);
         xmlwriter(xmlhaircolor);
         xmlwriter(xml_licenseclass);
         xmlwriter(xml_licenseclassname);
         xmlwriter(xml_licenseissuedate);
         xmlwriter(xml_licenseexpiresdate);
         xmlwriter(xml_licenseext);
         xmlwriter(xml_licenserestrict);
         xmlwriter(xml_licensedup);
         xmlwriter(xml_licenseheld);
         xmlwriter(xml_licenseseq);
         int a = 0;
         while (a < xml_abstractline.size()) {
              xmlwriter(xml_abstractline.get(a).toString());
              a++;
         int a1 = 0;
         while (a1 < xml_abstract_item.size()) {
              xmlwriter(xml_abstract_item.get(a1).toString());
              a1++;
         int a2 = 0;
         while (a2 < xml_abstract_violationdate.size()) {
              xmlwriter(xml_abstract_violationdate.get(a2).toString());
              a2++;
         int a3 = 0;
         while (a3 < xml_abstract_convictdate.size()) {
              xmlwriter(xml_abstract_convictdate.get(a3).toString());
              a3++;
         int a4 = 0;
         while (a4 < xml_abstract_sectviolated.size()) {
              xmlwriter(xml_abstract_sectviolated.get(a4).toString());
              a4++;
         int a5 = 0;
         while (a5 < xml_abstract_statute.size()) {
              xmlwriter(xml_abstract_statute.get(a5).toString());
              a5++;
         int a6 = 0;
         while (a6 < xml_abstract_file_number.size()) {
              xmlwriter(xml_abstract_file_number.get(a6).toString());
              a6++;
         int a7 = 0;
         while (a7 < xml_abstract_location_or_arn.size()) {
              xmlwriter(xml_abstract_location_or_arn.get(a7).toString());
              a7++;
         int a8 = 0;
         while (a8 < xml_abstract_vehicle_license.size()) {
              xmlwriter(xml_abstract_vehicle_license.get(a8).toString());
              a8++;
         int d = 0;
         while (d < xml_cline.size()) {
              xmlwriter(xml_cline.get(d).toString());
              d++;
         int e = 0;
         while (e < xml_dline.size()) {
              xmlwriter(xml_dline.get(e).toString());
              e++;
         int f = 0;
         while (f < xml_reqNameAddress.size()) {
              xmlwriter(xml_reqNameAddress.get(f).toString());
              f++;
         dflag = false;
         //writes the entag for dlnumber and dl record
    xmlwriter("</dl_record>");
         xml_abstractline.clear();
         xml_cline.clear();
         xml_dline.clear();
         xml_abstract_item.clear();
         xml_abstract_violationdate.clear();
         xml_abstract_convictdate.clear();
         xml_abstract_sectviolated.clear();
         xml_abstract_statute.clear();
         xml_abstract_file_number.clear();
         xml_abstract_location_or_arn.clear();
         xml_abstract_vehicle_license.clear();
         xml_reqNameAddress.clear();
         public static void xmlwriter(String writestring){     
              String filename = "U:\\dl.xml";
                   try {
                        FileWriter myFW = new FileWriter(filename, true);
                        BufferedWriter out = new BufferedWriter(myFW);     
    out.flush();
                        out.write(writestring);
                        out.newLine();
                        out.close();
                   } catch (IOException f) {
                        System.out.println("Error -- " + f.toString());
                   }// ends catch
    //     convenience to save typing, keep focus
         private static

    Ok, here is the snippet that I think is having problems
    static void xmlwriter(String writestring){
    String filename = "U:dl.xml";
    try {
    FileWriter myFW = new FileWriter(filename, true);
    BufferedWriter out = new BufferedWriter(myFW);
    out.flush();
    out.write(writestring);
    out.newLine();
    out.close();
    } catch (IOException f) {
    System.out.println("Error -- " + f.toString());
    }// ends catch
    I call this for everyline written, and as I watch the file bytes count up, I then see it reset to zero and start over. Could this be something to do with creating a new buffer for every line?

  • Appending objects in text file and searching.......

    I have been trieng to implement simple search operation on the class objects stored in the text file. but when i try to append new objects in the same file and search for the same; java.io.StreamCorruptedException is thrown. wat the problem is, that wen i append to the text file; it stores some header information before the actual object is stored and on the deserialization, this header information is causing the exception. the same header information is stored every time, i append to the file. anybody knws hw to get past it??? my code is as given below:
    package coding;
    import java.io.BufferedReader;
    import java.io.EOFException;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.PrintWriter;
    import java.io.Serializable;
         class Employee implements Serializable{
              private static final long serialVersionUID = 1L;
              String name;
              int id;
              public int getId() {
                   return id;
              public void setId(int id) {
                   this.id = id;
              public String getName() {
                   return name;
              public void setName(String name) {
                   this.name = name;
              public Employee(String name, int id) {
                   this.name = name;
                   this.id = id;
         public class FileSearch{
         public static void main(String[] args) throws IOException
              /*Entering the records into the file*/
              Employee ob = null;
              File file=new File("c:\\abc.txt");
              InputStreamReader isr=new InputStreamReader(System.in);
              BufferedReader stdin=new BufferedReader(isr);
              char fileExist='y';
              if(file.exists())
                   System.out.println("File already exists!!!");
                   System.out.println("Append New Records(press y) Or Search Existing File(press any other button)?:");
                   String strTemp=stdin.readLine();
                   fileExist=strTemp.charAt(0);
              else
                   System.out.println("File doesnt exist; creating new file......");
              if(fileExist=='y')
                   FileOutputStream fos=new FileOutputStream(file,true);
                   ObjectOutputStream oos=new ObjectOutputStream(fos);
                   char choice='y';
                   System.out.println("Enter records:");
                   while(choice=='y')
                        System.out.println("enter id:");
                        String id_s=stdin.readLine();
                        int id=Integer.parseInt(id_s);
                        System.out.println("enter name:");
                        String name=stdin.readLine();
                        ob=new Employee(name,id);
                        try
                             oos.writeObject(ob);
                             //count++;
                             oos.flush();
                        catch(Exception e)
                             e.printStackTrace();
                        System.out.println("Enter more records?(y/n)");
                        String str1=stdin.readLine();
                        choice=str1.charAt(0);
                   oos.close();
              /*Searching for the record*/
              System.out.println("Enter Record id to be searched:");
              String idSearchStr=stdin.readLine();
              int idSearch=Integer.parseInt(idSearchStr);
              try
                   FileInputStream fis=new FileInputStream(
                             file);
                   ObjectInputStream ois=new ObjectInputStream(fis);
                   int flag=1;
                   FileReader fr=new FileReader(file);
                   int c=fr.read();
                   for(int i=0;i<c;i++)
                        Object ff=ois.readObject();
                        Employee filesearch=(Employee)ff;
                        if(filesearch.id==idSearch)
                             flag=0;
                             break;
                   ois.close();
                   if(flag==1)
                        System.out.println("Search Unsuccessful");
                   else
                        System.out.println("Search Successful");
              catch(Exception e)
                   e.printStackTrace();
    }

    966676 wrote:
    All what I need to elect by who this word repeated. But I don't know really how to make It, maybe LinkedListYou should choose the simplest type fullfilling your needs. In this case I'd go for <tt>HashSet</tt> or <tt>ArrayList</tt>.
    or I dont know, someone could help me?You need to introduce a variable to store the actual name which must be resetted if an empty line is found and then gets assigned the verry next word in the file.
    bye
    TPD

  • How to Read from two file and write to another file --Please help !!

    Hi all,
    Please suggest me where i'm goin goin wrng.
    I have 2 flat files. one of them is the main file(Ann.dat) has a about 150,000 lines (each line has unique ID from 00001 to 45000) of data and the the other(Miss.dat) has a just a list of IDs that are no longer in use & have to be deleted from the first file(NewAnn.dat). (Note that Ann.dat is a tab delimitted file and Miss.dat is just a list of all invalid IDs)
    Below is my code. It doesn't do what I'm supposed to. Please suggest me or help me with a code to do it. What I'm trying to do is read each of the lines from the 2 files compare the ID in ann.dat with all the IDs in Miss.dat & if it doesn't match with the ID in Miss.dat write the whole line to NewAnn.dat. And do the rest with all the lines in Ann.dat.
    It could be a real dumb question. since i'm not a software professional, I consider myself to be newbie to programming. I desperately need your help.
    import java.io.*;
    import java.util.*;
    public class anntemp{
         public static void main(String[] args)
              String keyAnn ="";
              String keyMis="";
              String recAnn =null;
              String recMis =null;
              try{               
              FileReader fr=new FileReader("C:\\Tom\\Ann.dat");
              BufferedReader br=new BufferedReader(fr);
              int couter=0;
              while ((recAnn = br.readLine())!=null)
                   couter++;
                   keyAnn = recAnn.substring(0, recAnn.indexOf("\t"));
              FileReader fr1=new FileReader("C:\\Tom\\Miss.dat");
              BufferedReader br1=new BufferedReader(fr1);
              while((recMis = br1.readLine())!=null){
              keyMis = recMis.substring(0, recMis.indexOf("\t"));
                   if(keyAnn.equals(keyMis)){
         FileWriter fw=new FileWriter("C:\\Tom\\NewAnn.dat",true);
         BufferedWriter bw=new BufferedWriter(fw);
         PrintWriter pw=new PrintWriter(bw);
         StringBuffer writeValue = new StringBuffer();
         writeValue.append(recAnn);
                                                 pw.println(writeValue.toString());
         pw.flush();
              }catch (Exception expe){
                   System.out.println("In Exception ");
                   expe.printStackTrace();
    Thank you all in advance,
    br

    I think you need to close the files when you are done in the inner loop. Plus I think you'll be overwritting the file in the inner loop if more than one match. It might be easier to read the unused id file into a map at the start, and then loop up the id's from the master file in the map. You can put the unused id's in as the keys, and a Boolean.TRUE as the value (value won't matter). Then just check if the map contains the key for the id read from the master file. That should cut down on disk activity. This assumes the unused id file is smallish.

  • Get user input and find file and read it.....argh

    Ok, so I have to write a program that asks a user for the name of the file they want opened and then it is to read it and then display the max score and the minimum score on the file. also to display the average score on the file. Along with that it is supposed to display how many As, Bs, Cs, Ds, and Fs were on the file IE: a: 1 b: 3 c: 0 d: 4 f: 1. etc.
    Also, the next part is to have the program open the input file and then write all the information to an output file. I was able to do this and have the output file show the peoples names and their score along wtih their grade adn then the whole score average at the end of the output file....
    My question is how do I do the first part by asking the user for the name of file and then for the program to find the file and then display the max, min, average and how many letter grades the class got?

    this is what i have so far and the code before didnt work with JCreator, came up with lots of errors......
    What do i have to do to get the max value and min value to display along with the amount of As, Bs, Cs, Ds, and Fs????
    import java.io.*;
    class extest
    public static void main(String [] args) throws IOException
    // First, open the input file
    TextReader filein = new TextReader(new FileInputStream("test.txt"));
    // Read our number
    int x;
    x = filein.readInt();
    String [] first=new String[x];
    String [] last=new String[x];
    int [] score=new int[x];
    // load data from the input file test1.txt
    for (int i=0; i<x; i++)
    first=filein.readWord();
    last[i]=filein.readWord();
    score[i]=filein.readInt();
         WriteTestFile(first, last, score, x);
    public static void WriteTestFile(String f[], String last[], int score[], int x)
    double average=0;
    // Next, open the output file
    try
    PrintWriter fileout = new PrintWriter(
    new FileWriter("grade.txt") );
    // OK, now write to the file
    fileout.println(x);
    for (int i=0; i<x; i++)
    average=average+score[i];
    if (score[i]>90)
    fileout.println(f[i]+" "+last[i]+" " + score[i] +": "+"A");
    else if (score[i]>80)
    fileout.println(f[i]+" "+last[i]+ " " + score[i] + ": "+"B");
    else if (score[i]>70)
    fileout.println(f[i]+" "+last[i]+ " " +score[i] + ": "+"C");
    else if (score[i]>60)
    fileout.println(f[i]+" "+last[i]+ " " +score[i] + ": "+"D");
    else
    fileout.println(f[i]+" "+last[i]+" " +score[i] + ": "+"F");
    fileout.println("The average score of the class is "+average/x);
    // we're done with the output file
    fileout.close();
    catch (IOException e)
    throw new RuntimeException(e.toString());
    System.out.println("***** Welcome to the Grade Program! *****");
         System.out.println("");
         System.out.println("Please enter the name of the file you want to open: ");
         TextReader input = new TextReader(System.in);
         String fileName = input.readLine();
    System.out.println("The average of the scores is: "+average/x);
    System.out.println("The maximum score is: ");
    System.out.println("The minimum score is: ");
    System.out.println("Number of scores by letter grade:");
    System.out.println("A: ");
    System.out.println("B: ");
    System.out.println("C: ");
    System.out.println("D: ");
    System.out.println("F: ");

  • Read in a file and convert into Binary

    Hi there, i am new to java so plz give me a hand on this problem.
    I am suppose to read in a file(with whole bunch of different records), and what i need to do is convert the file into binary.....how do i do that??
    the original Q asked:
    Create a java program that will read the products file and write the products data into a java binary file. Adhere to good data typing conventions. That means, if a column in the input file is of type integer, then the data in that column should also be written to the output file in integer format. Same thing for String...
    Here is the code i have so far
    import java.io.*;
    class FileIO {
    /* Main method */
    public static void main(String[] args) throws IOException {
         FileReader file1 = new FileReader("test.txt");
         BufferedReader fileInput = new BufferedReader(file1);
         FileWriter file2 = new FileWriter("test1.txt");
         PrintWriter fileOutput = new PrintWriter(file2);
         String text;
         text = fileInput.readLine();
         //toBinaryString(text); <---i think there is something to do with the tobinary string but i am not sure
              System.out.println(text);
              fileOutput.println(text);
         // Close file
         fileInput.close();
         fileOutput.close();
    E-mail me directly if it's possible, thanks a lot~!!!!!

    Maybe not the answer the teacher is looking for, but I'd be highly tempted to point out that the file, regardless of what's in it, is already binary. Even if it's a text file, what do you think the characters are defined as? Bytes.

  • Copy one text file to another text file and delete last line

    Hi all wonder if someone can help, i want to be able to copy one text file to another text file and remove the last line of the first text file. So currently i have this method:
    Writer output = null;
             File file = new File("playerData.xml");
             try {
                   output = new BufferedWriter(new FileWriter(file, true));
                   output.write("\t" + "<player>" + "\n");
                   output.write("\t" + "\t" + "<playerName>" + playerName + "</playerName>" + "\n");
                   output.write("\t" + "\t" + "<playerScore>" + pointCount + "</playerScore>" + "\n");
                   output.write("\t" + "\t" + "<playerTime>" + minutes + " minutes " + seconds + " seconds" + "</playerTime>" + "\n");
                   output.write("\t" + "</player>" + "\n");
                   output.write("</indianaTuxPlayer>" + "\n");
                  output.close();
                  System.out.println("Player data saved!");
             catch (IOException e) {
                   e.printStackTrace();
              }However each time the method is run i get the "</indianaTuxPlayer>" line repeated, now when i come to read this in as a java file i get errors becuase its not well formed. So my idea is to copy the original file, remove the last line of that file, so the </indianaTuxPlayer> line and then add this to a new file with the next data saved in it. So i would end up with something like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <indianaTuxPlayers>
         <player>
              <playerName>Default Player</playerName>
              <playerScore>0</playerScore>
              <playerTime>null minutes null seconds</playerTime>
         </player>
         <player>
              <playerName>Default Player</playerName>
              <playerScore>0</playerScore>
              <playerTime>null minutes null seconds</playerTime>
         </player>
         <player>
              <playerName>Default Player</playerName>
              <playerScore>0</playerScore>
              <playerTime>null minutes null seconds</playerTime>
         </player>
    </indianaTuxPlayers>
    However after all day searching the internet and trying ways, i have been unable to get anything working, could anyone give me a hand please?

    I would go the XML route too, but for fun, open a file as a BufferedWriter and do this:
    void copyAllButLastLine(File src, BufferedWriter tgt) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(src));
        try {
            String previous= in.readLine();
            for (String current = null; (current = in.readLine()) != null; previous=current) {
                tgt.write(previous);
                tgt.newLine();
        } finally {
            in.close();
    }

  • Reading a file and changing one part of the file

    I am trying to read a file and then I want to change the first value on each line. The file I am reading is a .HEADER file. Which is just read in notepad I am just opening this like a txt file. I get no say at all how this file is created originally
    I want to change the value on the first line the a new title plus the ext .dat. The file is below. This stays the same format just with different values.
    ECG000 1 171 26112 9:14:56 23/04/2002
    ECG000 8 43(0) 8 127 79 -24066 0 AED trace
    I want to change the ECG000 to a new value eg Pat1.dat on the first line and Pat1 on the second line. When I read this file in and output to the dos window I get ECG000 0 0 0 and that is it. Any ideas why this is happening and how I can replace the values in the file??
         private void FileExt() throws IOException
              System.out.println("In function");
              BufferedReader br = new BufferedReader(new FileReader("c:\\Projects\\FirstSupport\\ECG000.HEADER"));
              String s;
              Vector data = new Vector();
              ECGFile = new FileWriter("c:\\Projects\\FirstSupport\\ECG.txt",true);
              System.out.println("Reading the file");
              while ((s = br.readLine()) != null)
              data.add(s);
              System.out.println(s);
              System.out.println("Finished");
              String label = s.substring(0, s.indexOf(" "));
              System.out.println(label);
              String newLabel = (label+".dat");
              System.out.println(newLabel);
         }

    I think this is what you're looking for:     private void FileExt() {
              java.util.List data=new ArrayList();
              String s;
              try {
                   BufferedReader br=new BufferedReader(new InputStreamReader(
                        new FileInputStream(new File("ECG000.HEADER"))));
                   while ((s = br.readLine()) != null)  {
                        data.add(s);
                        System.out.println(s);
                   br.close();
              catch (FileNotFoundException fnfe) {
                   System.out.println("Input file not found");
                   return;
              catch (IOException ioe) {
                   ioe.printStackTrace();
                   return;
              ListIterator li=data.listIterator();
              try {
                   PrintWriter ECGFile=new PrintWriter(new FileOutputStream(
                        new File("ECG.txt")));
                   while(li.hasNext()) {
                        s=(String)li.next();
                        if (s.substring(0, 6).equals("ECG000")) {
                             s="Pat1.dat"+s.substring(6, s.length());
                        ECGFile.println(s);
                   ECGFile.close();
              catch (FileNotFoundException fnfe1) {}
         }Mark

  • Reading .txt files and put it into a TextArea

    Hi all,
    I got a problem! I have to make something like a messenger.
    I want to put the written text into a .txt file, after that I have to get the text out of the .txt file and put in into a TextArea.
    I would ike it to to that like this:
    ">User 1
    Hello!
    >User 2
    Hi!
    Now here are my questions:
    1: What is the moet easy way to do this ?
    2: How could i put Enters into a .txt file with Java ?
    3: How could i read all the text from the .txt file and put it into a TextArea WITH ENTERS ?
    Thanks for your help!
    Greetings, Jasper Kouwenberg

    use JTextArea.read(new FileReader(fileName)) for reading.
    and JTextArea.write(new FileWriter(fileName)) for writing.
    The enters should be ok if the user press enter and adds a new line ("\n") to the text area component.
    It will save the enter in the text file and load it correctly back to the text area.
    If you want to add enter programmatically just add "\n" string to the text area component.

  • Read from a file and write back

    Hi,
    I'm trying to read from a text file, and stor into a vector of vectors.
    This part works fine
    then i want to randomly split the vector into 2 different vectors a training set and a test set.
    this part woks fine too.
    now i want to write each of these vectors to a text file........this is the part i'm stuck on.
    some of my code is below:
    public static void main(String[] args)
              Vector Train;
              //Vector Test;
              Split s = new Split();
              Vector data = s.readFile("diabetes.txt");
              Vector Test = s.split(data);
              Train = s.getTrainingVector();
              //Training.txt = s.writeToFile(Training, "Training.txt");
              //Test.txt = s.writeToFile(data, "Test.txt");
              File Training = new File("Training.txt");
              File Testing = new File("Test.txt");
              FileWriter out = new FileWriter(Training);
              for(int i =0; i<Train.size(); i++)
                   out.write(Train.get(i));
                   out.write("\n");
              out.close();
              FileWriter out2 = new FileWriter(Test);
              for(int i =0; i<Test.size(); i++)
                   out2.write(Test.get(i));
                   out2.write("\n");
              out2.close();
         }Can anybody help?
    Cheers

    i've tried that but i'm getting this error:
    cannot resolve symbol
    symbol : method write (java.lang.Float)
    location: class java.io.FileWriter
    out.write((Float)(InnerVec.get(i)));
    does it have to be Strings?

  • How to read in a file and change the column attributes

    Hi,
    I'm new to java and i'm stuggling to find a way to read in a text file and perform calculations on the data, such as to normalise it.
    What in want to do is normalise the data by finding the greatest value in a column and then divide all the other values in the column with that value.
    I know how to read a file in and store each line in a vector but for this problem i think i need to store each column in an array, but i'm not sure how to do this.
    Can anyone help please?
    Thanks

    Hi,
    I'm new to java and i'm stuggling to find a way to
    read in a text file and perform calculations on the
    data, such as to normalise it.
    What in want to do is normalise the data by finding
    the greatest value in a column and then divide all
    the other values in the column with that value.
    I know how to read a file in and store each line in a
    vector but for this problem i think i need to store
    each column in an array, but i'm not sure how to do
    this.
    Can anyone help please?
    ThanksI think this should work but I wrote it out without completely thinking about it (hopefully to get things started).
    So if you had this:
    age height earnings
    0 2 100
    1 3 50
    2 1 0
    For the age column you'd take 2 as the largest and then divide 0 and 1 by two to get 0, .5.
    First build up test files that seperate the columns in different ways. With spaces, tabs, and the ASCI Control character for null ( I think it's 0 ). Your program should detect
    numbers and spaces, tabs control character, commas and periods (for money). Because numbers don't have spaces it should be easy to keep track of which column
    you're in.
    Store each line into a 3D String array with each index containing a String built up from the chars scanned in on each line, when a blank area is found followed by another
    number iterate the column index. When you come to the end of the line set column == 0 and row+1.
    private String[][][] test = new String[2][6][1];
    20     3      11      14      44       0
    4      5       7      80      91      49
    test[0][0][0] would be row 1 col 1 value 1 ((20))
    test[0][1][0] would be r1, c2, v1 ((3))
    test[1][0][0] would be r2, c1, v1 ((4))
    test[1][2][0] would be r2, c3, v1 ((7))
    test[1][5][0] would be r2, c6, v1 ((49))
    package source.Final;
    import javax.swing.*;
    import java.io.*;
    public class S7
         public static void main(String[] args)
              getContents();
              System.exit(0);
         public static void getContents()
              String lineSep = System.getProperty("line.separator");
              char c = ' ';
              int iterator = 0;
              int i = 0;
              int charNum = 1;
              int lineCount = 1;
             //declared here only to make visible to finally clause
             BufferedReader input = null;
             BufferedWriter out = null;
             try {
                         String line = null;
                          * This implementation reads / writes one line at a time
                          * using the buffered reader / writer Java classes.
                         input = new BufferedReader( new FileReader( "C:\\Scan file test\\Read\\test1.txt" ));
                           out = new BufferedWriter( new FileWriter( "C:\\Scan file test\\Read\\test2.txt" ));
                         //input = new BufferedReader( new FileReader( "C:\\Scan file test\\Read\\booked_policies1.txt" ));
                           //out = new BufferedWriter( new FileWriter( "C:\\Scan file test\\Write\\booked_policies1.txt" ));
                         //input = new BufferedReader( new FileReader( "C:\\Scan file test\\Read\\booked_policies2.txt" ));
                           //out = new BufferedWriter( new FileWriter( "C:\\Scan file test\\Write\\booked_policies2.txt" ));
                         //input = new BufferedReader( new FileReader( "C:\\Scan file test\\Read\\booked_policies3.txt" ));
                           //out = new BufferedWriter( new FileWriter( "C:\\Scan file test\\Write\\booked_policies3.txt" ));
                         out.write( "Character\tLine Number\tCharacter Number\tAscii Value" + lineSep );                     
                              while (( line = input.readLine()) != null)
                              i = 0;
                              charNum = 1;
                              iterator = 0;
                              while( i < line.length() )
                                               c = line.charAt(iterator);                                             
                                            if( (int)c == 0 || (int)c == 9 )
                                                 break;
                                            else if( c >= '[' && c <= '_')
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            else if( c <  ' ' )// && (int)c != 0 && (int)c != 9  )
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            else if( c >  ';' && c <= '@' && c != '=')
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            else if( c >= '!' && c < '"' )
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            else if( c >  'z' && c < '~' )
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            else if( c == '%' )
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            else if( c >  '~' )
                                                 {out.write( "["+c+"]\t\t"+"["+lineCount+"]\t\t"+"["+charNum+"]\t\t\t"+"["+(int)(c)+"]"+lineSep );}
                                            charNum += 1;
                                               iterator += 1;
                                               i++;
                                    lineCount += 1;
             catch (FileNotFoundException ex) {ex.printStackTrace();     System.out.println("File not found.");}
                 catch (IOException ex){ex.printStackTrace();               System.out.println("IO Error.");}
             finally{ try{ if( input != null ) input.close();                if( out != null ) out.close();}
                    catch (IOException ex){ex.printStackTrace();        System.out.println("IO Error #2.");}
        }

  • Adding line to txt file and then rename

    Hello there. I am trying to create a class that will add a line to a txt file and then if the nuber of lines are greater than 5 it will rename the file.
    I think I have solved it with this class.
    My problem is that the file2.renameTo does not work does anyone have any suggestions why?
             public void CopyLines(String string, String location, String fileName) throws IOException {
                 BufferedReader inputStream = null;
                 PrintWriter outputStream = null;
                   GregorianCalendar calendar = new GregorianCalendar(Locale.UK);
                boolean b=false;
                 try {
                     int counter = 0;
                      File file2 = new File(location + fileName);
                      ArrayList arrays = new ArrayList();
                      if (file2.exists()){
                     inputStream =
                         new BufferedReader(new FileReader(file2));
                     String l;
                     while ((l = inputStream.readLine()) != null) {
                          arrays.add(l);
                         counter++;
                     outputStream =
                         new PrintWriter(new FileWriter(location + fileName));
                      if (!arrays.isEmpty()){
                           for(int i= 0; i<arrays.size();i++){
                              outputStream.println(arrays.get(i));
                     outputStream.println(string);
                     if (counter>5){
                          String newFileName = location + fileName + calendar.getTime().getTime();
                          b = file2.renameTo(new File(newFileName));
                 } finally {
                     if (inputStream != null) {
                         inputStream.close();
                     if (outputStream != null) {
                         outputStream.close();
             }

    What is ". . .does not work. . ."?

  • Java loading text file and doing stuff help

    Hello,
    Can anyone help me with this, I just don't know where to start..
    I need to create a java program which will load up a text file. The text file must be no bigger than 1000 characters (so somewhere there needs to be an exception I am guessing)
    Once loaded, it needs to run some methods on the text file which each return a single statistical count, the methods need to count things like number of white space, number of vowels, frequency of each vowel (this would not need to return a single count but maybe update some sort of array?) , number of printable characters and number of consonants.
    Any help would be very good.
    Dean

    Thanks for the help so far
    But first things first, I should start at the
    beginning.
    I am thinking maybe start with something like from
    the Sun tutorial for 'CopyCharacters.java'.
    So we have the first part of the program that loads
    up the txt file....
    (I really would like to have GUI for this, but I
    can worry about that once the actual program is
    working
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    public class CopyCharacters {
    public static void main(String[] args) throws
    IOException {
    FileReader inputStream = null;
    FileWriter outputStream = null;
    try {
    inputStream = new
    FileReader("input_characters.txt");
    Right, now its time to actually read what is in the
    file and use some of the statements you have
    suggested, can anyone help me get started with this?
    Dean
    public class DeanHomeworkAssignment {
    public static void main(String args[]) {
    //Put your code here
    }There ya go, that should get you started.
    Start by writing the code to open the file.
    This isn't that difficult.

Maybe you are looking for

  • Multiple Numeric Limit Test - Evaluate Post and Status Expression

    We have a Multiple Numeric Limit Test where the limits for one of the measurements is a function of one of the other measurements. In the Post-Expression there are two expressions that set the low and high limit based on one of the readings. But the

  • Moving config to new device

    Hi All, As the subject suggests I have been set the task of exporting a config to a new device.  The new device will have the outside interface assigned by the service provider.  The current ASA has the following in the config access-list non-priorit

  • How do spaces work - assign applications to a space

    I have read through a number of documents. I have assigned a number of apps to Space 2. If I open them when I am space 1, I thought they would open automatically in space 2. Am I being stupid or missing the point about how how app assignment is suppo

  • Rename Windows Host Server?

    I have a Windows 2008R2 server hosting an installation of VMware Server 2.0.2 which runs 2 VM's. I want to rename the 2008R2 server from ABC to DEF. The name change is the only change, IP addresses and everything else will remain as is. Will this hav

  • Project closure - labor cost from WIP to COGS a/c upon closure

    Dear Projects experts, We are implementing v12.2.3, In Oracle PA, for a specific project type, our business users want labor cost first charged to a WIP Cost a/c, and upon closure of the project, the cost should be moved to a designated COGS a/c. Is