0

How to read from a textfile and display specific words(numbers) from that textfile based on different groups?

I have a txt file that contains this:

[computers]
keyboards =3
mouse  =5

[animals]
cow =10
pig =5

The numbers will always be changed by another program.

I want to make a form that can display the like this:

Cars:    3 keyboards/n
         5 mouse

animals 10 cows
        5  pigs

I don`t know how to do that. I know how to read from file but the next...

This is how my frame will look package nioCount;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class FrameTest extends JFrame {

private JPanel contentPane;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                FrameTest frame = new FrameTest();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public FrameTest() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnCount = new JButton("Count");
    btnCount.setBounds(80, 202, 89, 23);
    contentPane.add(btnCount);

    JButton btnResetCount = new JButton("Reset");
    btnResetCount.setBounds(268, 202, 89, 23);
    contentPane.add(btnResetCount);

    JTextArea txtrComputers = new JTextArea();
    txtrComputers.setText("Computers:");
    txtrComputers.setBounds(24, 59, 84, 22);
    contentPane.add(txtrComputers);

    JTextArea txtrKeyboards = new JTextArea();
    txtrKeyboards.setText("3 keyboards");
    txtrKeyboards.setBounds(147, 43, 130, 23);
    contentPane.add(txtrKeyboards);

    JTextArea txtrMouses = new JTextArea();
    txtrMouses.setText("10 mouses");
    txtrMouses.setBounds(147, 77, 130, 22);
    contentPane.add(txtrMouses);

    JTextArea txtrAnimals = new JTextArea();
    txtrAnimals.setText("Animals:");
    txtrAnimals.setBounds(24, 133, 84, 22);
    contentPane.add(txtrAnimals);

    JTextArea txtrDogs = new JTextArea();
    txtrDogs.setText("3 Dogs");
    txtrDogs.setBounds(147, 110, 130, 23);
    contentPane.add(txtrDogs);

    JTextArea txtrCats = new JTextArea();
    txtrCats.setText("15 cats");
    txtrCats.setBounds(147, 152, 130, 23);
    contentPane.add(txtrCats);
}

}

and when i press count button it will count for each category..

This is what my .txt file contains:

[phone]
bad=1
good=30

[animals]
bad=10
good=30
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
  • Your examples seem to contradict each other, but what you probably want is a map. – Compass Oct 28 '14 at 14:22
  • i don`t know why u say my examples contradict each other. i just wanna know how to read from that file and output into a jtextarea only the numbers from that file – Vlad Enacho Oct 28 '14 at 14:34
  • `[computers]` -> `Cars` in your example. Are we turning computers into cars? Is it a typo? – Compass Oct 28 '14 at 14:37
  • was my bad. i want to output the value of each object for each category into a jframe. i don`t know how to output them. i just tried to give an example: category : Animals , Computers, cars. – Vlad Enacho Oct 28 '14 at 14:41

2 Answers2

0

A possible way to do this is a BufferedReader:

public class ReadTextFile {

    public static void main(String[] args) {
        BufferedReader br = null;
        try {
            String currentLine;

            br = new BufferedReader(new FileReader("file.txt"));

            while ((currentLine = br.readLine()) != null) {
                System.out.println(currentLine);
                //test for your strings from here
                //("[computers]", etc.)
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

I don't know what exactly you want to do, but I think you would be happier with XML.

jntme
  • 602
  • 1
  • 5
  • 18
  • i have a program from a camera that can measure some objects. the camera output`s an file with bad measurements or good ones. let`s say i have two kind of objects, first object is a phone and second one is an mouse. If the phone doen`s have the dimmensions that i want camera writes in that doccument the number of phones are bad or god. same with mouse. the doccuments is like this [CATEGORY] ( phones) bad= 10 ( 10 means the number of 10 bad phones) god= 15 ( 15 means the number of good phones that respect`s my dimmensions) same with phone – Vlad Enacho Oct 28 '14 at 14:51
  • making this code is going me crazy.. don't know how to wire all thoes info`es u gave – Vlad Enacho Oct 28 '14 at 15:22
0

We have the following objects to keep track of.

  1. Category (i.e. Computer, Animal)
  2. Descriptor (i.e. Keyboard, Pig)
  3. Count (i.e. 5, 10)

We have the following dependencies.

  1. A Category can have 1 or more Descriptors.
  2. A Descriptor has one Count.

There are several approaches to doing this, but I'll go with the one easiest based on your description here.

The numbers will always be changed by another program

I assume this means we need to be able to track Descriptor and change it, possibly without knowing what the Category is. For example, an example method of setValue("Keyboard", 10);

We don't know the Keyboard is related to the computer, and searching through all the categories to find the Keyboard is time-intensive.

Since you say you know how to read the file, I'll leave that up to you, and instead describe what to do with pseudocode.

First of all, we need two Maps. For simplicity, I'll use HashMaps.

HashMap<String, ArrayList<String>> categoryToDescriptor = new HashMap<>();
HashMap<String, Integer> descriptorToCount = new HashMap<>();

The first map stores all of our categories, the second map stores all of our counts.

Let's say we take the text input and come across "[Computer]". We need to add this to our category map:

categoryToDescriptor.put("Computer", new ArrayList<String>);

In your case, you'd have a variable to parse out Computer, and all the variables.

After that, we get descriptors and values, such as "keyboard=5"

We do two things with this info. You can parse it out, but I'll hardcode it.

String descriptor = "keyboard";
int count = 5;

categoryToDescriptor.get("Computer").add("keyboard");
descriptorToCount.put("keyboard",5);

We are now mapping categories to a list of descriptors, and descriptors to their associated counts.

Using entryset iteration, we can do something like this to print out all the values.

for (Map.Entry<String, ArrayList<String>> entry : categoryToDescriptor.entrySet()) {
    System.out.println("Category: " + entry.getKey());
    ArrayList<String> listOfDescriptors = entry.getValue();
    for(String descriptor: listOfDescriptors) {
        System.out.println("Descriptor: " + descriptor + " Value: " + descriptorToCount.get(descriptor);)
    }
    System.out.println("");//line feed between categories
}

Additionally, to update a value of a descriptor, all we have to do is:

descriptorToCount.put("keyboard", newValue);
Community
  • 1
  • 1
Compass
  • 5,867
  • 4
  • 30
  • 42
  • i use this public int[] ReadFromFile(final String[] tokens) throws IOException { final int[] counters = new int[tokens.length]; BufferedReader br; br = new BufferedReader(new FileReader("D:/test.txt")); String str1 = ""; while ((str1 = br.readLine()) != null) { for (int i = 0; i < tokens.length; i++) if (str1.contains(tokens[i]))//if the line contains the token counters[i]++;// increase counter for the index of the token } return counters; } to read the file it is good or wrong.. i`m new in java... – Vlad Enacho Oct 28 '14 at 15:16
  • @VladEnacho then it should not be that difficult to wire it up. You just need to set the values while reading. – Compass Oct 28 '14 at 15:18
  • This is what i've done so far. need some help i`m stuck. [link](http://txt.do/omb8) – Vlad Enacho Oct 28 '14 at 16:15
  • @VladEnacho The HashMaps are meant to be fields, and not instantiated at every loop. It looks like you just copied this stuff into the other answer. The goal is to understand how and why it works, not just make it work. – Compass Oct 28 '14 at 16:25
  • i understand from ur description , the thinking , but i don`t know how to connect them together to make it work, and yes i copied that stuff and tryed to do something. i`m noob in java. i try to learn i never saw a hashmap like this with all this stuff together. – Vlad Enacho Oct 28 '14 at 16:33
  • @VladEnacho Step by step. Implement the BufferedReader. Make sure the inputs are working. Then implement the category Map. Make sure each category is working and getting its values. Finally, implement the descriptor map. The solution doesn't have to work all at once. It should be built bit by bit. – Compass Oct 28 '14 at 16:36
  • When u say "Then implement the category Map" u talk about " HashMap> categoryToDescriptor = new HashMap<>();" ? right?> – Vlad Enacho Oct 28 '14 at 16:51
  • @vladEnacho Yes. You should make it a static Hashmap and declare it within the class if you're implementing everything in the main method. – Compass Oct 28 '14 at 16:52
  • Thank you compass for all ur help. But i still don`t know how to deal with it. i have to learn if i want to make it. Sorry for spending your time.. – Vlad Enacho Oct 28 '14 at 17:00
  • `public class ReadTextFile { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("D:\\test.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { System.out.println(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } final HashMap>categoryToDescriptor = new HashMap<>(); ` Better Now? – Vlad Enacho Oct 28 '14 at 17:09
  • You should probably put it into a new question if you're having issues implementing the provided solutions. – Compass Oct 28 '14 at 17:22
  • did that already .. here`s the link [link](http://stackoverflow.com/questions/26613602/hashmap-help-read-from-file-print-to-console-jtextarea?noredirect=1#comment41840325_26613602) – Vlad Enacho Oct 28 '14 at 17:26