Solved

How to update file?

Posted on 2004-10-06
18
211 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
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
 

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Free Alternative to JIRA 4 91
Java / Linux and Regular Expressions 11 71
Cipher Configuration on Apache HTTPD 4 53
Spring Framework HTTPSession management 1 23
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…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

920 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

16 Experts available now in Live!

Get 1:1 Help Now