Solved

How to update file?

Posted on 2004-10-06
18
237 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 4
  • +2
18 Comments
 

Author Comment

by:izomax
ID: 12245569
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
ID: 12245629
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
ID: 12245643
use the code i posted in your previous q
0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 

Author Comment

by:izomax
ID: 12245648
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
ID: 12245729
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
ID: 12245736
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
ID: 12245752
> hi objects! long time no see!

:)
0
 

Author Comment

by:izomax
ID: 12245773
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
ID: 12245792
Yeah something like that whould be the more efficient method I talked about.
0
 
LVL 92

Expert Comment

by:objects
ID: 12245801
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
ID: 12245803
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
ID: 12246683
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
ID: 12246732
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
ID: 12247052
>>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
ID: 12247099
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
ID: 12247256
>>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
ID: 12247578
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
ID: 12341858
8-)
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

728 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