• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 246
  • Last Modified:

How to update file?

If I have a file that contains:

MSFT 18
INTC  223
EMC   1

I am writing a function:

update(string symbol, int quote)

After I have opend the file and do readLine, how can I update a value of a symbol? (Say MSFT 20)
0
izomax
Asked:
izomax
  • 5
  • 4
  • 4
  • +2
1 Solution
 
izomaxAuthor Commented:
Here's my skeleton code, can anyone help me with the updat part? Thanks!

public void updatQuote(string symbol, unsigned long quote) throws BrokerErrorException
    {
      String ref = null;
      String ticker;
      String value;
      int positionSpace;

      FileInputStream file = new FileInputStream("nasdaq");
      BufferedReader in =   new BufferedReader(new InputStreamReader(file));
            
      while((ref = in.readLine())!null)
      {
            
            positionSpace = ref.indexOf('');
            ticker = ref.subString(0, positionSpace);
            value = ref.subString(positionSpace+1, positionSpace+2);            
            
            if(ticker.equalsIgnoreCase(symbol))
            {            
                  if((quote >=1) && (quote<= 300))
                  {
                        //update value
                  
                  }      
            }
            else
            {
                  BrokerException err = new BrokerErrorException(1);
                  throw err;
            }
      }

      file.close();
    }
0
 
Tommy BraasCommented:
Hi izomax,

If you don't have to have the file in the format above, but can use the following format:
    MSFT=18
    INTC=223
    EMC=1

then you can use simple property files!

If that is the case, you can use the following very simple code:

    public void updateQuote(String symbol, long quote) throws BrokerErrorException
    {
        String ref = null;
        String ticker;
        String value;
        int positionSpace;

        try
        {
            FileInputStream infile = new FileInputStream("nasdaq");
            Properties props = new Properties();
            props.load(infile);
            infile.close();

            props.setProperty(symbol, Long.toString(quote));
            FileOutputStream outfile = new FileOutputStream("nasdaq");
            props.store(outfile, "Your comments go here");
            outfile.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new BrokerErrorException(1);
        }
    }

Cheers!

\tt
0
 
objectsCommented:
use the code i posted in your previous q
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
izomaxAuthor Commented:
Hi  thanks.

But the file format can't be changed, so there'll always be a blank space between the symbol and value.
0
 
Tommy BraasCommented:
izomax,

I'm not sure what objects has posted earlier (hi objects! long time no see!), but this code will do the trick:

    public void updateQuote(String symbol, long quote) throws BrokerErrorException
    {
        try
        {
            Reader infile = new BufferedReader(new FileReader("nasdaq"));
            StringBuffer strbuf = new StringBuffer();
            char[] buff = new char[1024];
            int len = 0;
            while ( (len = infile.read(buff)) != -1)
            {
                strbuf.append(buff, 0, len);
            }
            infile.close();
           
            String[] data = strbuf.toString().split(" \n\r");
            FileOutputStream outfile = new FileOutputStream("nasdaq");
            for (int i = 0; i < data.length; i++)
            {
                if (data[i].equals(symbol))
                {
                    data[i + 1] = Long.toString(quote);
                    i++;
                }
                outfile.write(data[i].getBytes());
            }
            outfile.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw new BrokerErrorException(1);
        }
    }

\tt
0
 
RuadRauFlessaCommented:
Hmmm... How many would there be at any given time. If it is not alot you could try and read everything to an array or something in memmory change it there and then rewrite the whole file. I know it is propably not the most efficient way of doing it but you will actually notice a speed increase in some cases. That is unless the item that you are searching for is in the beginning of the file and you have like 300 items that it has to read in before even searching for the correct one.

But it should suffice.
0
 
objectsCommented:
> hi objects! long time no see!

:)
0
 
izomaxAuthor Commented:
Hi objects,

You meant this?


File f = new File("book.java");
File newf = new File("book.java.new");
BufferedReader in = new BufferedReader(new FileReader(f));
PrintWriter out = new PrintWriter(new FileWriter(newf));
String line = null;
while (null!=(line=in.readLine()))
{
   if (!line.equals("book2"))
   {
      out.println(line);
   }
}
in.close();
out.close();
f.delete();
newf.renameTo(f);
0
 
RuadRauFlessaCommented:
Yeah something like that whould be the more efficient method I talked about.
0
 
objectsCommented:
yes, and modify the middle bit to make any changes required.
eg.

File f = new File("book.java");
File newf = new File("book.java.new");
BufferedReader in = new BufferedReader(new FileReader(f));
PrintWriter out = new PrintWriter(new FileWriter(newf));
String line = null;
while (null!=(line=in.readLine()))
{
     String[] tokens = line.split(" ");
     if (tokens[0].equals("MSFT"))
     {
        line = tokens[0]+" "+20;
     }
     out.println(line);
}
in.close();
out.close();
f.delete();
newf.renameTo(f);
0
 
objectsCommented:
though if you're doing lots of updates you may be better off reading the file into memory and operating on that.
Then saving it to disk once all updates are done.

depends on your requirements.
0
 
CEHJCommented:
If you use the class below, you can do:

String newRecord = "MSFT 2001";
StringList sl = new StringList();
sl.read("x.txt");
// Chnage the old line to the new one
sl.set(0, newRecord);
sl.save("x.txt");


//SNIP ========================================================


import java.io.*;
import java.util.ArrayList;

/**
 *  A utility class the allows a text file to be
 *  treated as a collection of Strings
 *
 * @author     CEHJ
 * @created    29 February 2004
 */
public class StringList extends ArrayList {

  /**
   *Constructor for the StringList object
   */
  public StringList() {
    super();
  }

  public void read(InputStream in) {
    read(new InputStreamReader(in));
  }


  public void read(Reader r) {
    String line = null;
    BufferedReader in = null;
    try {
      in = new BufferedReader(r);
      while ((line = in.readLine()) != null) {
        add(line);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      try {
        in.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }

  }

  /**
   *  Constructor for the StringList object
   *
   * @param  fileName  The file to open
   */
  public void read(String fileName) {
    try {
      read(new FileReader(fileName));
    }
    catch(IOException e) {
      e.printStackTrace();
    }
  }

  /**
   *  Save the String to named file
   *
   * @param  fileName  The name of the file to save to
   */
  public void save(String fileName) {
    PrintWriter out = null;
    try {
      out = new PrintWriter(new FileOutputStream(fileName), true);
      for (int i = 0; i < size(); i++) {
        out.println((String) get(i));
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      if (out != null) {
        out.close();
      }
    }
  }

}

0
 
objectsCommented:
If you're going to read the file into memory it'll be a lot easier to manage as a Map.

Map prices = new HashMap();
File f = new File("book.java");
BufferedReader in = new BufferedReader(new FileReader(f));
String line = null;
while (null!=(line=in.readLine()))
{
     String[] tokens = line.split(" ");
     prices.put(tokens[0], new Integer(2)));
}
in.close();

// to update price

prices.put("MSFT", new Integer(20));


Let me know if you need more details
0
 
CEHJCommented:
>>it'll be a lot easier to manage as a Map.

Only if you

a. know exactly what you're looking for
b. are not interested in being able to look lines up by index
c. not interested in a reusable solution for text file manipulation
0
 
RuadRauFlessaCommented:
I'd go with object's view on the situation. Since there is nothing wrong with taking the time and making it reusable and the index thing is much faster than you might imagine and you can always look it up by name as well.
0
 
CEHJCommented:
>>and the index thing is much faster than you might imagine and you can always look it up by name as well.

Not sure what you mean there. There is no indexing in objects' approach and you'd *have* to look it up by name

>>Since there is nothing wrong with taking the time and making it reusable

It's inherently non-reusable since it's bound to a particular file format
0
 
RuadRauFlessaCommented:
Yeah but it is re-usable for that type of file structurew since you might want to use it somewhere else somewherer in the unforseable future.

never mind we can go on about this for years to come. Thread is closed.
0
 
CEHJCommented:
8-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

  • 5
  • 4
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now