Java Read TXT as Array?

Discussion in 'Mac Programming' started by finnschi, Mar 21, 2011.

  1. finnschi macrumors 6502

    Joined:
    Dec 30, 2008
    Location:
    Hamburg, Germany
    #1
    hey guys I have a small problem and I hope you can help me out! :rolleyes:

    So I want to programm a little Java Programm that does the Following:

    1. Read a TXT File, each line is a Data Set, each line and each data set has a fixed length

    2. Sort the data

    3. Output stuff

    Here is my Programm so far, it only reads the given txt file and outputs it.

    Code:
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    
    public class DateiLesen {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		String Artikel, Artnr, Artbez, Menge, Herst;
    		Double Preis, Maxpreis, Minpreis;
    		Byte Lieferz;
    		int  Best, Maxbest, Minbest;
    		int z = 0;
    		
    		//Aufruf UP zum Lesen eines Satzes aus Datei
    		Artikel = ReadIn(z);
    	
    	// Erster Aufruf des UP, bereits vor der Schleife
    		
    		while (Artikel != null)				// Beginn der eigentlichen Programmschleife
    		{
    			System.out.println(Artikel);
    			System.out.println();
    			Artnr  = Artikel.substring(0,8);
    			Artbez = Artikel.substring(9,39);
    			Menge  = Artikel.substring(40,42);
    			Herst  = Artikel.substring(58,99);
    			Best	  = Integer.parseInt(Artikel.substring(44,47));
    			Maxbest   = Integer.parseInt(Artikel.substring(49,52));
    			Minbest   = Integer.parseInt(Artikel.substring(54,57));
    			Preis     = Double.parseDouble(Artikel.substring(101,107));	
    			Maxpreis  = Double.parseDouble(Artikel.substring(109,115));
    			Minpreis  = Double.parseDouble(Artikel.substring(117,123));
    			Lieferz   = Byte.parseByte(Artikel.substring(124));
    			
    			System.out.println("Artikelnummer		: " + Artnr);
    			System.out.println("Artikelbezeichnung	: " + Artbez);
    			System.out.println("Mengeneinheit		: " + Menge);
    			System.out.println("Maximalbest		: " + Maxbest);
    			System.out.println("Minimalbest		: " + Minbest);
    			System.out.println("Hersteller		: " + Herst);
    			System.out.println("Preis			: " + Preis);
    			System.out.println("Maximalpreis		: " + Maxpreis);
    			System.out.println("Minimalpreis		: " + Minpreis);
    			System.out.println("Bestand			: " + Best);
    			System.out.println("Lieferzeit		: " + Lieferz);
    			System.out.println("--------------------------------------------------");
    			z = z + 1;
    	
    			Artikel = ReadIn(z);
    			
    		}
    
    			
    		}
    	
    	
    	// Unterprogramm zum Einlesen der Datens‰tze
    	public static String ReadIn(int i)
    	{
    		// Deklaration/Initialisierung notwendiger lokaler Variablen
    		int pos = 127 * i;			// Berechnung der Datensatz-Position, nur bei S‰tzen fester L‰nge mˆglich
    		String Einzelartikel;
    
    		// Lesen der einzelnen Datens‰tze
    		// Verwendung der try-catch-Anweisung zwecks Exception-Handling
    		try
    		{
    			File Datei            = new File("/artikel.txt");
    			FileReader FileReader = new FileReader(Datei);
    			BufferedReader Reader = new BufferedReader(FileReader);
    			
    			Reader.skip(pos);								// Positioniere auf den n‰chsten Datensatz
    			Einzelartikel = Reader.readLine();	   			// Datensatz wird gelesen
    			Reader.close();									// Lesepuffer wird geschlossen
    			return Einzelartikel;							// Zur¸ck zum rufenden Programm mit Datensatz
    															// Gibt <null> zur¸ck, falls kein Datensatz mehr
    		}
    		catch(Exception Fehler)
    		{
    			System.out.println("Es trat folgender Fehler auf: " + Fehler);	// Keine weitere Fehlerbehandlung
    			return null;									
    		}
    	}
    	
    		
    	}
    	
    
    
    Ignore the comments, they are in german :p

    this is the txt file:
    Code:
    51100210 Holzfenster einfach 6*15       ST 0160 0800 0150 Vereinigte Bauelementewerke Hennigsdorf   0495.80 0629.25 0499.80 5
    51100211 Holzfenster einfach 10,5*15    ST 0410 0500 0100 Vereinigte Bauelementewerke Hennigsdorf   0529.95 0595.00 0499.80 4
    51100212 Holzfenster Verbund 6*15       ST 0620 1500 0300 Fensterbau Halle                          0563.00 0625.95 0545.95 5
    51100213 Holzfenster Verbund 10,5*15    ST 0800 1500 0300 Fensterbau Halle                          0619.00 0649.00 0569.95 4
    51100214 Holzfenster Thermoscheibe 6*15 ST 0570 1200 0250 Bauelementewerke Erfurt                   0665.50 0665.80 0583.95 4
    51100215 Holzfenster Thermosch. 10,5*15 ST 0275 1200 0200 Bauelementewerke Erfurt                   0629.50 0679.80 0595.85 6
    51300220 Aussentuer ATM 10,5*21         ST 0125 0400 0100 Holzbau Neubrandenburg                    1150.00 1384.00 1139.95 3
    51300221 Aussentuer ATM 10,5*21 M       ST 0380 0400 0100 Holzbau Neubrandenburg                    1440.50 1495.95 1180.00 5
    51300222 Aussentuer ATM 10,5*21 S       ST 0101 0370 0080 Vereinigte Bauelementewerke Erfurt        2760.50 2830.22 2740.00 4
    51400223 Tuerfluegel TV 9*20 L          ST 1100 1050 0195 Holzwerke Oranienbaum                     0929.00 0995.00 0899.95 2
    51400224 Tuerfluegel TV 9*20 R          ST 0920 1050 0195 Holzwerke Oranienbaum                     0929.00 0995.00 0899.95 2
    51600225 Futtertuer TV-F14,5 9*20 L     ST 0720 0860 0150 Vereinigte Bauelementewerke Stralsund     1499.50 1595.80 1490.50 4
    51600226 Futtertuer TV-F14,5 9*20 R     ST 0684 0860 0150 Vereinigte Bauelementewerke Stralsund     1529.80 1595.80 1490.50 4
    51700227 Blendrahmentuer TG2-B 9*20 L   ST 0012 0480 0080 Forstwirtschaftsbetrieb Waren             1859.20 1899.00 1595.00 3
    51700228 Blendrahmentuer TG2-B 9*20 R   ST 0310 0480 0080 Forstwirtschaftsbetrieb Waren             1838.00 1899.00 1595.00 3
    52100230 Likolit-Belag Extra            QM 0100 2000 0500 Linoleumwerke Kohlmuehle                  0038.15 0047.95 0038.15 5
    52100231 Radeberger Treppenbelag        QM 0210 0800 0200 Bauproduktion Radeberg                    0029.55 0029.55 0028.95 1
    52100232 Stahl-Pur-Bit-Dachelement      QM 1150 3000 0800 Holz- und Leichtmetallbauelemente Leipzig 0109.95 0119.00 0099.30 1
    61100240 Brausekabine                   ST 0005 0080 0010 TGA Magdeburg                             0962.50 0983.45 0910.00 2
    61100241 Praezisionsverdunkl.-Anl.15*20 ST 0007 0160 0040 Licht- und Sonnenschutzanl. Friedrichroda 0316.60 0333.20 0316.60 5
    
    So how would I treat each Data set (i.e Max Preis ..) as a single variable so I can do calculations with it , and sort them using bubble sort?
     
  2. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    You have a couple of options. One would be to make a Class and have instances of this class represent individual articles. Then you can write a routine that sorts an Array(List, etc.) by any of the instance variables.

    Another option that's a bit more primitive would be to have a number of co-arrays. Each array stores one piece of information about an article, so "across" the arrays, items at the same index are related to the same article. The problem here would be if you simply sorted the max price array, you'd lose the correlation to the other arrays. You'd need to write your sort such that it sorted all of the arrays based on the ordering of max price.

    I would greatly prefer option number one, that's what OOP is all about after all, but the second would certainly work.

    -Lee
     
  3. notjustjay macrumors 603

    notjustjay

    Joined:
    Sep 19, 2003
    Location:
    Canada, eh?
    #3
    You would want to create a Class that encapsulates all of the data associated with one data set. You could call the class DataSet, for example.

    Then your reader would read a line of the text file, parse out all the individual bits of data, then create a new instance of the DataSet class which would store all of the bits of data for that one set. Your main program could contain a Vector of all of the DataSet instances.

    Once you've finished reading your file, your Vector will contain all of the DataSets and then you can write a sort routine that sorts them based on whatever criteria you want (probably the index number, but up to you).
     
  4. finnschi thread starter macrumors 6502

    Joined:
    Dec 30, 2008
    Location:
    Hamburg, Germany
    #4
    That sound very good, but I have no Idea how I could accomplish this in Real Code, could you maybe show me what I would have to change in my code to parse something to another class?
     
  5. notjustjay macrumors 603

    notjustjay

    Joined:
    Sep 19, 2003
    Location:
    Canada, eh?
    #5
    There are tutorials available on the web that show you the mechanics for defining new classes and how to use them. Here's a link I found, for example:

    http://home.cogeco.ca/~ve3ll/jatutor4.htm

    Have a good look at the "Box" class that author defines.

    Here's another link:

    http://download.oracle.com/javase/tutorial/java/concepts/index.html

    The example object/class discussed here is a Bicycle.

    Understanding how to work with classes and objects is a huge step in working with Java (or any other OO language) so I think it would be very good for you to work through how to adapt this concept to your data sets. Let us know if you have any questions.

    Hope that helps!
     
  6. finnschi thread starter macrumors 6502

    Joined:
    Dec 30, 2008
    Location:
    Hamburg, Germany
    #6
    Thx for that bu I already know how classes and methoths etc work, my Problem is that I don't know how I could save the stuff that is written in the txt file as an Array so another class can access it :confused:
     
  7. lee1210 macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #7
    So you have this section already:
    Code:
    			Artnr  = Artikel.substring(0,8);
    			Artbez = Artikel.substring(9,39);
    			Menge  = Artikel.substring(40,42);
    			Herst  = Artikel.substring(58,99);
    			Best	  = Integer.parseInt(Artikel.substring(44,47));
    			Maxbest   = Integer.parseInt(Artikel.substring(49,52));
    			Minbest   = Integer.parseInt(Artikel.substring(54,57));
    			Preis     = Double.parseDouble(Artikel.substring(101,107));	
    			Maxpreis  = Double.parseDouble(Artikel.substring(109,115));
    			Minpreis  = Double.parseDouble(Artikel.substring(117,123));
    			Lieferz   = Byte.parseByte(Artikel.substring(124));
    This defines the layout of the lines and what each data item is. Instead of storing that to a bunch of local variables, you would instead, say, pass the String you read into a constructor for your new SpitzeArtikel class. The constructor would assign the values to instance variables and you'd get back an instance of SpitzeArtikel that represents the article described by the line you passed in. Now that you have this SpitzeArtikel you'd use add on a (for example) ArrayList, so you'd have:
    Code:
    ArrayList<SpitzeArtikel> meineArtikeln = new ArrayList();
    while(canRead) {
      SpitzeArtikel einArtikel = new SpitzeArtikel(ReadIn(x));
      meineArtikeln.add(einArtikel);
    }
    Collections.sort(meineArtikeln,artikelBeiMaxPreis);
    You'd have to define the class atikelBeiMaxPreis, which is a Comparator. You could do it anonymously, make it an inner class, whatever. At the end of this you'd have meineArtikeln sorted by max price, ready to display.

    -Lee
     
  8. notjustjay macrumors 603

    notjustjay

    Joined:
    Sep 19, 2003
    Location:
    Canada, eh?
    #8
    You should look further into the concepts of data encapsulation and using classes to represent your data, and not just Java utilities like BufferedReaders and Strings.

    I'm afraid I don't read German so I can't tell exactly what the data bits in your code mean, but the concept is that you have a bunch of data sets. Each data set contains an article number, a name (I think?), and a bunch of numerical data attributes.

    To me this maps perfectly into creating a class called DataSet that has class members representing the article number, name, data, etc. Each DataSet object will store all of the information about one of your data sets. Then you can create a collection (like the ArrayList that lee1210 suggests) of DataSet objects to work with.

    Again have a look at the tutorials I linked to, for example the second one where they work with Bicycles. Each Bicycle has a set of data associated with it: its cadence, it's speed, and its current gear. The code in the tutorial shows how to instantiate two different Bicycles and set the data for each one. I see you doing the same thing, except instead of Bicycles you have DataSets, and instead of cadence and speed you have article numbers, names, and all that stuff.
     

Share This Page