File I/O
File I/O
File I/O
File I/O
File I/O
File I/O File I/O File I/O File I/O File I/O File I/O File I/O File I/O
File I/O File I/O
File I/O
Go Back  Xtreme Visual Basic Talk > > > File I/O


Reply
 
Thread Tools Display Modes
  #1  
Old 12-20-2010, 08:51 AM
Navop Navop is offline
Newcomer
 
Join Date: Nov 2010
Posts: 9
Default File I/O


Newbie at this

Did a lot of reading on input file text, but never really found what I needed
(Maybe I missed a tutorial or a thread, maybe someone can point me in the right direction.)

The text file i'm reading has no real colums or space that are the same.

Code:
6472    4-40/5-40 Plastic Nut                                      			4    1.00 
 9599 	B4 MIP CVD, Complete Set                          				Pr.  35.00
 6473    Shock Bushings                                             			4    1.00 
 9600 	B4 Motor Plate                                    				1     7.00
 6475    Preload Spacers, collars & cups. 4 thicknesses, 4         			Set   5.00 
 9601 	B4 Top Shaft                                      				1    10.00
         
 9602 	B4 Top Shaft Spacer                               				1     2.00
 6573    Diff Thrust Washer & Bolt                                  			2    3.00 
 9603 		B4 Slipper Pad                                    			2     7.00
 6574    Precision Diff Thrust Balls, 5/64"                         			6    2.00 
 9604 		B4 Slipper Hub                                    			1     8.00
But the following is true for this one text file:

Item# = 6 characters
Description = 82 characters
QTY = 4 characters
Cost = 4 characters

Trying to load the text file so I can minipulate it like to remove the " " in the begginging and the end of each colum to make it more compact.(I know how to use the right$ , mid$ commands)

Once finish I need to dump the text file back to a text file so I can import in excel or dump it directly to an excel spread sheet containing the colums mentioned above.

Not all text file colums are the same so I need a way to be able to change the space count. e.g. item # in one text file is 6 characters long while in another it might be 9 characters long.

Thanks for all the help in advance

Last edited by Flyguy; 12-20-2010 at 08:59 AM.
Reply With Quote
  #2  
Old 12-20-2010, 04:03 PM
jantje jantje is offline
Junior Contributor
 
Join Date: Dec 2004
Posts: 255
Default

Just use fixed sized variables and you're all set.
Preferably put them in a UDT and read the file as records.
Code:
Type SomeRecord
  Item as String * 6
  Description as String * 82
  QTY as String * 4
  Cost as string * 4
End Type
Then after reading you can simply Trim its values and you are all set.
Reply With Quote
  #3  
Old 12-20-2010, 04:25 PM
passel's Avatar
passelFile I/O passel is offline
Sinecure Expert

Super Moderator
* Guru *
 
Join Date: Jun 2003
Location: Upstate New York, usa
Posts: 8,024
Default

To import into excel, the normal way to separate the columns in the text file is either use CSV (Comma separated Values), or use a tab character between each column.
Since some of your descriptions have comma's in them, the tab character between fields would seem to be the way to go, although you could put double quotes "around your strings" and then still be able you use comma's as your field separators.
__________________
There Is An Island Of Opportunity In The Middle of Every Difficulty.
Miss That, Though, And You're Pretty Much Doomed.

Last edited by passel; 12-20-2010 at 04:32 PM.
Reply With Quote
  #4  
Old 12-20-2010, 06:02 PM
AtmaWeapon's Avatar
AtmaWeaponFile I/O AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

If your ultimate destination is Excel, there's not really any need for you to write a program. When you open a .txt file, Excel should start a wizard that lets you tell it how your data is shaped. Fixed-width columns are one of the choices.

But if what you said later is true ("some columns have more characters than normal") all bets are off. If there's not many of them you can hand-correct them. If there's a lot of them you probably need to do some programmatic massaging. Here's how I'd attack it.

Fixed-width records are useless from the viewpoint of the .NET File I/O classes. You can use Legacy I/O, but since your columns are of varying widths it might not turn out pretty. Since whitespace is the only delimiter *and* whitespace can occur in the 2nd column *and* it might precede the first column, you've got a bit of a task. I think the parsing algorithm would look like this:
Code:
* Read a line and trim it to get rid of starting/ending whitespace.
* Find the first space character in the line; column 1 is from 0 to that index.
* Find the last space character in the line; column 4 is from there to the end.
* Find the last non-whitespace character before column 4; that's the end of column 3.
* Find the first whitespace character before column 3's end; that's the start of column 3.
* Column 2 is from the end of column 1 to the beginning of column 3.
This seems to do the trick, but needs some work before I'd consider using it in production. It was written to be readable, but doesn't do the kinds of things that make a program maintainable. In a few places I favored saving characters at the expense of readability. It more or less implements the algorithm above, and will only fall apart if you're holding out some more rules for the data; I figure from this starting point you ought to see how to make it work for just about anything.
Code:
Module Module1

    Sub Main()
        Dim lines = ParseFile()
        For Each parsedLine() As String In lines
            For Each token As String In parsedLine
                Console.Write("|{0}| ", token)
            Next
            Console.WriteLine()
        Next
    End Sub

    Private Function ParseFile() As IEnumerable(Of String())
        Dim output As New List(Of String())()
        Using reader As New IO.StreamReader("data.txt")
            While Not reader.EndOfStream
                Dim parsedLine() As String = ParseLine(reader.ReadLine())
                If parsedLine IsNot Nothing Then
                    output.Add(parsedLine)
                End If
            End While
        End Using

        Return output
    End Function

    Private Function ParseLine(ByVal line As String) As String()
        Dim output(3) As String

        Dim trimmedLine = line.Trim()
        If trimmedLine.Length = 0 Then
            ' Don't try and parse empty lines
            Return Nothing
        End If

        ' Find and extract column 1: 0 to first whitespace
        Dim column1End As Integer = trimmedLine.IndexOf(" ")
        output(0) = trimmedLine.Substring(0, column1End - 1)

        ' Find and extract column 4: last whitespace to end
        Dim column4Begin As Integer = trimmedLine.LastIndexOf(" ")
        output(3) = trimmedLine.Substring(column4Begin + 1, trimmedLine.Length - column4Begin - 1)

        ' Find and extract column 3: Non-whitespace group before column 4
        Dim column3End As Integer = column4Begin
        While Char.IsWhiteSpace(trimmedLine(column3End))
            column3End -= 1
        End While

        Dim column3Begin As Integer = column3End - 1
        While Not Char.IsWhiteSpace(trimmedLine(column3Begin))
            column3Begin -= 1
        End While

        output(2) = trimmedLine.Substring(column3Begin + 1, column3End - column3Begin)

        ' Column 2 must be between 1 and 3; pull everything and trim it
        output(1) = trimmedLine.Substring(column1End, column3Begin - column1End).Trim()

        Return output
    End Function

End Module
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #5  
Old 01-05-2011, 09:48 PM
Navop Navop is offline
Newcomer
 
Join Date: Nov 2010
Posts: 9
Default

Thanks
for info, but like I said I'm a total newbie at this, not sure where to put the code in VB 10

Tried to figure it out, get a whole bunch of error... lol

So can someone point me in the right direction so I can read up on how-to load a text file and
maybe a few good working example that I can test and play with to learn ...


thanks
Reply With Quote
  #6  
Old 01-06-2011, 08:58 AM
AtmaWeapon's Avatar
AtmaWeaponFile I/O AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

Quote:
not sure where to put the code in VB 10
Create a new "Console Application" project and replace the entire contents of Module1.vb with my code. There should be no errors. If there are any, post what the errors are and I'm certain I can tell you what's wrong.

If you're looking for a more general tutorial, File I/O in .NET is a good start, as is the documentation for the System.IO namespace. The File and Stream I/O topic on MSDN is also a good starting point.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #7  
Old 01-11-2011, 07:42 PM
Navop Navop is offline
Newcomer
 
Join Date: Nov 2010
Posts: 9
Default

AtmaWeapon thanks for all the help in advance, but when running the code I get the following error for the following code line:

' Find and extract column 1: 0 to first whitespace
Dim column1End As Integer = trimmedLine.IndexOf(" ")
output(0) = trimmedLine.Substring(0, column1End - 1)

Error = ArgumentOutOfRangeException was unhandled
Lenght cannot be less than zero.
Parameter name: lenght

Also I get the following:

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Reply With Quote
  #8  
Old 01-11-2011, 07:58 PM
Navop Navop is offline
Newcomer
 
Join Date: Nov 2010
Posts: 9
Default

Ok, never mind got rid of error by editing the data.txt file
Reply With Quote
  #9  
Old 01-11-2011, 08:00 PM
Navop Navop is offline
Newcomer
 
Join Date: Nov 2010
Posts: 9
Default

Ok it worked I know for a fact but wher edoes all the info go?

I see the cmd window open super quick, then it closes...
Reply With Quote
  #10  
Old 01-12-2011, 08:35 AM
AtmaWeapon's Avatar
AtmaWeaponFile I/O AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,500
Default

In the IDE, choose "Run without debugging" (usually Ctrl+F5). This makes the program add a "press any key to continue..." prompt at the end. The data is simply dumped to the screen. The code was meant as a demonstration of parsing the file, not an application that does anything with it.
__________________
.NET Resources
My FAQ threads | Tutor's Corner | Code Library
I would bet money 2/3 of .NET questions are already answered in one of these three places.
Reply With Quote
  #11  
Old 01-12-2011, 07:31 PM
Navop Navop is offline
Newcomer
 
Join Date: Nov 2010
Posts: 9
Default

oh ok thanks
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Forum Jump

Advertisement:





Free Publications
The ASP.NET 2.0 Anthology
101 Essential Tips, Tricks & Hacks - Free 156 Page Preview. Learn the most practical features and best approaches for ASP.NET.
subscribe
Programmers Heaven C# School Book -Free 338 Page eBook
The Programmers Heaven C# School book covers the .NET framework and the C# language.
subscribe
Build Your Own ASP.NET 3.5 Web Site Using C# & VB, 3rd Edition - Free 219 Page Preview!
This comprehensive step-by-step guide will help get your database-driven ASP.NET web site up and running in no time..
subscribe
File I/O
File I/O
File I/O File I/O
File I/O
File I/O
File I/O File I/O File I/O File I/O File I/O File I/O File I/O
File I/O
File I/O
 
File I/O
File I/O
 
-->