File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Help!  Need to write out a amount after string has certain values in it.  Must add and read file. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help!  Need to write out a amount after string has certain values in it.  Must add and read file." Watch "Help!  Need to write out a amount after string has certain values in it.  Must add and read file." New topic
Author

Help! Need to write out a amount after string has certain values in it. Must add and read file.

Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
Trying to locate a String that starts with 070 positions (0,3)
Then has **H1H** on line (8,14)
Then I want to have a variable Justin to write the Amount in positions (50,59)
Currently it only reads one line (doesn't loop thru)

I know this is a simple thing I am missing. I have looked a split, loops, tokenizer don't know what will do this best.


Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
Trying to locate a String that starts with 070 positions (0,3)
Then has **H1H** on line (8,14)
Then I want to have a variable Justin to write the Amount in positions (50,59)
Currently it only reads one line (doesn't loop thru)


I don't understand a thing. Could you explain a little clearer ?


JDBCSupport - An easy to use, light-weight JDBC framework -
Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
I have a file justin.txt

I have lines of data

020 23456**H7H** 67890 1234567899
070 23455**H1H** 34567 0000544300
070 23455**H3H** 34567 0000544300
020 23456**H7H** 67890 1234567899
070 23455**H1H** 34567 0000544300
070 23455**H3H** 34567 0000544300

right now I can read the file and get the 020 in console and that is it or I can have the whole string write out. Just one string writes out in the console.

I want to go through grab all records that have a 070 **H1H** and grab that amount
Then go to the next one and grab the next amount.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
I presume you are familiar with the methods of the String class eg 1 2 3 4 5.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Don't use StringTokenizer any more.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19072
    
  40

Basically, your program reads one line, and processes it -- but you want to process all of the lines. Maybe a loop would help here? Read the next line and repeat? And repeat until out of lines?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
I am asking if true and first three char = 070 to write out.

I am getting everything - items that are other than 070 and true and false items.

I added the loop and that helped but I am still not there.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
You are still making things too complicated. You don't need to count the Strings up to 233; what happens if somebody writes a file with 232 lines in?

You need the following alterations to make it safe from resource leaks, even without changing the reading logic, and you also should have different catches for FileNotFound and IO Exceptions, rather than plain Exception. It may be possible to move the FileNotFound try, so you can repeat the attempt if you fail to find the file first time.You need to learn to use a loop until you find the last line. You will have to learn this idiomor the alternative versionThe first version will stop when you encounter the last line, but you may end up with a blank line. The second version will also stop if you encounter a 0-length line.

Your assigning the String to lots of different names is not necessary; forget about that. Instead, use the methods I quoted earlier to find whether you have 070 and H1H at particular positions in your lines. As an alternative you can try the String#split method, but with lines of fixed length that may be unnecessary.
Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
With the finally and catches you added ..I get a null pointer exception.. I took out most the code and I still get the null pointer exception.

Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
Thank you Ritchie....Contains made it do exactly what I wanted.

But I would like to code correctly if you could finish helping me with that finally and catch problem I would appreciate it.

But contains - 070 and HV1 worked to just give me those records. All the rest I had looked at. The API definitions really don't make sense to me.

I really don't know how to program most effectively - I don't re-use - I just put everything in one class and run it.

Any and all help is appreciated. If there is someway you know to get me out of these bad habits I would apprecitate it.
Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
Why don't you want to use a tokenizer anymore?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Have you read what it says in the API about Tokenizer? It says there not to use it.
You can probably find H1H using the startsWith method and an offset.

Agree the API documentation is difficult to read until you have had lots of practice.

The reason for "finally" is to make sure the reader is definitely closed. To keep it in scope for the "finally" it has to be declared before the inner try. You must initialise it to something; the only thing you can initialise to without risking an Exception is null. So there is a risk of the value being null when you try to close the reader, and you have to test for != null in the finally. But the finally might throw an IOException, so you have to have that bit in a try. So you end up with two try blocks inside each other. It looks complicated, but it is a standard technique which makes absolutely sure your file is released at the end of that method.

Suggested change to opening the Reader:So if you give the wrong name for the file, you try again. If you give the wrong name again, you might go round and round for ever. Note you have relocated the FileNotFoundException handling, so you can get rid of it farther down.
There are several ways to get keyboard input; most people nowadays would use Scanner rather than JOptionPane.
Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
Having a problem with the finally at bottom of code eclipse editor is telling me to delete it.

Also editor telling me to rename
BufferedReader MAYFILE = new BufferedReader(new FileReader("C:\\CASHPROOFREPORTS.txt"));

Lastly trying to add a group of numbers and write out that total and getting the error stream is closed. But shouldn't be closed.

all help is greatly appreciated.



Justin Char
Ranch Hand

Joined: Mar 05, 2007
Posts: 76
I have been also getting an error

"Errors exist in reuired project(s)"

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 40052
    
  28
Justin Charpenter wrote:I have been also getting an error

"Errors exist in reuired project(s)"

There is nothing like being specific, and that error message is nothing like being specific. Have you any idea what it means?

Where is that sun.security package from? My javac tool couldn't find it. It can be hazardous to use classes starting with "sun." because some of them are experimental and might be removed from later releases of Java. But if you search for something, Eclipse has a habit of finding the most obscure types first, so that type might be there by mistake.

You appear to be closing your Counter (probably shouldn't have capital "C") in the loop. That may cause your problems about closed stream. You will need to close it in a finally. So . . .
  • wrap opening the Counter stream in a try-catch for FileNotFoundException.
  • That would be similar to what I showed yesterday about opening your reading stream.
  • Close your writing stream in a finally
  • At first I thought you can reuse the finally you close the reading stream in, but that would readSo I thought, this chap has got too much going on in one method. You ought to have a reading method, a calculation method and a writing method.

    You are using some old-fashioned code, choosing DecimalFormat when you could create the String with % tags using the String#format() method instead.

    There is nothing wrong with the finally block. Maybe you have Eclipse set in real fusspot mode, which is useful, but you may need to take the warnings with a pinch of salt.

    You have managed to declare MAYFILE (which name ought not to be in upper-case) twice. You have BufferedReader MAYFILE twice; on the second occasion you should simply write MAYFILE without "BufferedReader". Eclipse is trying to be helpful by suggesting renaming as an option.

    If you are a beginner, you would probably do well to stop using IDEs (eg NetBeans, Eclipse) until you have more experience. IDEs can be more of a hindrance than a help to beginners. Have a look at this recent thread about text editors.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I agree

    I just don't know how to create multiple methods that talk to each other.

    Also, I am at a point now where it does what I need it to do except I can't get the numbers to add.

    I converted them ot integers and still can't get them to add. I thought I create a varible like
    Justin+=(line.substring(106,115)) but it doesn't work.

    I print out the numbers I want to add together twice. I just can't get them to add. I can't count them. Just can't add them for some reason.

    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    Try getting a List<String> to contain your text. Use the reading method to populate the List, use the calculations method to take the Strings out of the List (in turn) and parse the Strings for the bits you want to add. Return a value from that method (probably best as a BigDecimal) and then use a writeToFile method to put it in a new file.

    Beware: BigDecimal is immutable. You can use its add() method to add two BigDecimals together, but you need another BigDecimal reference to store the result. Have a look at its constructor; you might be able to get it to take values directly from Strings.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I am having a problem finding a solution using list or big decimal.

    I have three numbers printing out as a String

    I converted them to integers - I want to add them together -

    It can't be that difficult to add some numbers together.

    I know I am missing something simple. I am going to smack my self when I figure it out or someone helps me.

    Is there any additional information you can give me.

    Thank you in advance Justin

    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    Is your last code complete? You are parsing your amounts to an int. Try printing out the amount multiplied by 2; that will confirm you are doing arithmetic with it. If you can't do arithmetic then it won't compile.

    I can't see anywhere that you are adding the amounts in the code you provided.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    System.out.println(aInt);

    all three amounts come out under this variable (aInt)

    I need to somehow separate these three variables to add them together

    Or

    Find a way to add all three amounts that print from aInt.

    It is probably something simple and I am going to slap myself but that is what I am trying to do.

    If they were three seperate variables I could take care of it.

    If it was coming off the database I would not have problems. But being I am reading it from a file I am running into issues.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I did multiply * 2 and it multiplied the first number but not the other two.

    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I put this in my while stmt. Just prints the 3 numbers that are in aInt variable..

    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    Please show us what you have already and a snippet of your text file, because I tried out your code and there weren't any Strings containing 070 and **HV1 in what you posted earlier.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I can't add an attachment says cannot send txt files..Just copy and put in text file. Delete (//)commented lines just notes so you know what numbers I am grabbing.

    070 32**HV1

    0819200R0000000000000000000000000000000000000000000000000000000000000000043016443820000000000000000000000000000000000000000


    //1644382 this is the number in above string looking for to add with next two
    0701201**HV1

    0819200R0000000000000601495945000000000000130115724100000000000000749000018003888260203320800035923000206210000000000000000


    //388826 2 nd number I want to add in above string 8 char field for each number
    0701801**HV1

    081920090000000000000000000000000000000000000000000000900220702000000000000000000000000000000000000000000000000000000000000

    //00000000 this field is 0 zeros but could have 10 won't always be three numbers I am adding .



    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    I presume your lines were to be made into single lines; I had to change some of the numbers to get 1644382 and 388826 into the right positions. I also managed to run your code and got a file called C:\Count04eJan09zz.txt which has this content:
    16443821644382
    0388826388826
    00000000
    What is happening is that you are joining the String (writing with values like "0388826") and the number together, giving 0388826388826. Note the leading 0 disappears from the number component. I had to edit your code severely. Several things I had to change
  • Incorrect indentation: please always use spaces not tabs
  • A few declarations moved to more appropriate locations
  • Change the numbers so I started at 91 for 1644382
  • Remove most comments and unused imports
  • And, as often happens with beginners, delete the 50% of the code not actually being used. That includes one Reader (you had two but only used one) and the NumberFormat, which you might reinstate later.
  • There are some inappropriatedly named variables: MAYFILE justin etc. I ended up with this:Conclusions
    What is happening is that you can extract the requisite numbers from the text in the file, but the method of counting scores of 0s before the number is very brittle and unreliable. Whoever designed that file format should be shot
    You appear to have a number called iSum, but you are repeatedly setting that to 0. Although you are correctly adding to that number, because it is declared and reset inside the loop, it never becomes a running total. I would suggest a long rather than an int, to reduce the risk of overflow errors.
    Please change the fill string method (which you appear not to be using) to use a proper for loop rather than a while running backwards. Please add {} and proper indentation to that loop.

    If you are after a total of the numbers you are parsing, you will have to move the declaration of iSum out of the loop. You may find Scanner and Formatter easier to use for handling text files. They may save you all this messing around with NumberFormat objects.

    I think I have give you enough to keep you busy for at least 10 minutes
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    Took me more than 10 min (smile)

    The 2033208 is the number I am looking for (but only that one number) as you can see my output shows three numbers and I don't know how to make it just my total number. I have looked at scanner and couldn't get it to work either.
    Output
    1644382
    2033208
    2033208
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    2033208? I was looking for 388826. You have the numbers you are looking for in different positions in their Strings. That makes it even harder to parse; in fact unless you know the values are in exactly the same place in each String, maybe impossible to parse.

    Your iSum will now be calculating the total. Rather than Integer.value Of(String) use Integer.parseInt(String). You can write iSum to a file or print it from that method.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    The numbers are in exactly the same place everytime. The one I sent you I had to paste so maybe things moved around. I couldn't send as attachment on here because tells me doesn't except txt files.

    The problem is there are three numbers associated with iSUM and when It prints I get three results for iSUM
    I only want to get one the total which as you can see above I get one of the numbers I am adding and two total amounts. The total Amounts are accurate. I just don't know what to do to get one result and have it be the total amount of 2033208.

    When I do System.out.println(j) I get the three amounts I am adding.

    When I do a System.out.println(iSUM) I get Three amounts - one amount being the first line I am adding and the following two the total I need. But I need it to print once not twice.

    If you can help me with that I put up another post for at least a day (smile)

    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    You are adding something to iSum evry time the loop executes, so the total should gradually increase. You should be able to check that with the original file and the original numbers (114 or whatever). Try changing the bit about adding to something like this
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I added this ("long Justin = iSUM += i;") to the last code you sent me and it now does what I needed it to do.
    I tried using scanner like you said had problems. I will wait one day and then hopefully you can help me understand the scanner method.

    Thank you very much for your assistance you saved me.
    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I was wrong it isn't working still

    console:

    08A EDUCATION PRINCIPAL: 1644382
    08A EDUCATION PRINCIPAL: 2033208
    08A EDUCATION PRINCIPAL: 2033208

    I still can't get it to print out the total 2033208 by itself. It prints all 3 amounts everytime.

    This is driving me nuts. Current Code below.

    This shouldn't be that difficult. (smile) Maybe I am just not as smart as I thought I was.

    Justin Char
    Ranch Hand

    Joined: Mar 05, 2007
    Posts: 76
    I got it!!!

    I am good....Thank you...Really I am good....(smile)

    Dum Dum Dum mistakes...

    Thank you for all your help!!
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40052
        
      28
    Well done
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: Help! Need to write out a amount after string has certain values in it. Must add and read file.