Solved

How to update file?

Posted on 2004-10-06
18
200 Views
Last Modified: 2010-07-27
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
Comment
Question by:izomax
  • 5
  • 4
  • 4
  • +2
18 Comments
 

Author Comment

by:izomax
Comment Utility
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
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
use the code i posted in your previous q
0
 

Author Comment

by:izomax
Comment Utility
Hi  thanks.

But the file format can't be changed, so there'll always be a blank space between the symbol and value.
0
 
LVL 14

Expert Comment

by:Tommy Braas
Comment Utility
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
 
LVL 3

Expert Comment

by:RuadRauFlessa
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
> hi objects! long time no see!

:)
0
 

Author Comment

by:izomax
Comment Utility
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
 
LVL 3

Expert Comment

by:RuadRauFlessa
Comment Utility
Yeah something like that whould be the more efficient method I talked about.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 86

Accepted Solution

by:
CEHJ earned 500 total points
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>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
 
LVL 3

Expert Comment

by:RuadRauFlessa
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>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
 
LVL 3

Expert Comment

by:RuadRauFlessa
Comment Utility
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
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
8-)
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now