开发者

Read text line and put in to the JTable

hey

i have text file shown as below.

11/2/2010     cat    6

11/2/2010     cat    3

11/2/2010     dog    4

11/2/2010     cat    11

11/3/2010     cat    1

11/3/2010     dog    3

11/3/2010     cat    8

i have in every month this kind of text file. Above figure shows the part of  the te开发者_StackOverflow社区xt file. so then i want to read this text  using java to Jtable.

i Have used StringTokanizer And Arreaylist to ceate this. Unfotunately i couldn't done it. SO PLS HELP ME........

So i want below result to jTable using java program.

  date     animal  total  count

11/2/2010   cat     20      3

11/3/2010   cat     9       2


You don't need a StringTokenizer (in fact, it's not recommended). Just get the input line by line using BufferedReader, and do a String split:

List<Array> data = new ArrayList<Array>();
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String line;

// Read input and put into ArrayList of Arrays
while ((line = in.readLine) != null) {
    data.add(line.split("\\s+"));
}

// Now create JTable with Array of Arrays
JTable table = new JTable(data.toArray(), new String[] {
    "date", "animal", "total", "count"});


test with : http://crysol.org/es/node/819

or

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

public class Reader {

    public Reader() {
        // TODO Auto-generated constructor stub
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new InputStreamReader(
                                        new FileInputStream("sample.txt")));
            Map<String, Object[]> result = new LinkedHashMap<String, Object[]>();

            while (reader.ready()) {
                String line = reader.readLine();
                String[] values = line.split("\\s+");
                String key = values[0] + "\t" + values[1];

                String label = values[0];
                String date = values[1];
                Integer sum = 0;
                Integer count = 0;
                if (result.containsKey(key)) {
                    sum = (Integer) ((Object[]) result.get(key))[2];
                    count = (Integer) ((Object[]) result.get(key))[3];
                } else {

                }
                result.put(key, new Object[]{label, date,
                        sum + Integer.parseInt(values[2]), count + 1});
            }
            ArrayList arrayList = new ArrayList(result.values());

            /* interate and print new output */
            /*
             * for (String key : result.keySet()) { Integer sum =
             * result.get(key); Integer count = result2.get(key);
             * System.out.println(key + " " + sum + "\t" + count); }
            */
            JTable table = new JTable(new AnimalTableModel(arrayList));
            panel.add(new JScrollPane(table));
            reader.close();
            frame.setContentPane(panel);
            frame.setVisible(true);
            frame.pack();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Reader();
    }

    public class AnimalTableModel implements TableModel {
        final Class[] columnClass = new Class[]{String.class, String.class,
                Integer.class, Integer.class};
        final String[] columnName = new String[]{"Date", "Animal", "Sum",
                "Count"};
        List values = null;

        public AnimalTableModel(List values) {
            this.values = values;
            // initilize values
        }

        @Override
        public void addTableModelListener(TableModelListener l) {
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnClass[columnIndex];
        }

        @Override
        public int getColumnCount() {
            return columnClass.length;
        }

        @Override
        public String getColumnName(int columnIndex) {
            return columnName[columnIndex];
        }

        @Override
        public int getRowCount() {
            return values.size();
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return ((Object[]) values.get(rowIndex))[columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public void removeTableModelListener(TableModelListener l) {
        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            // TODO FOR EDITABLE DT
        }
    }
}


You will have to populate the data to a map from the given file.I will give you an example as to how to populate the data.

public class AnimalMapping {

    public static void main(String[] args) {

        Object[][] data = { { "11/2/2010", "cat", 6 },
                { "11/2/2010", "cat", 3 }, { "11/2/2010", "dog", 4 },
                { "11/2/2010", "cat", 11 }, { "11/3/2010", "cat", 1 },
                { "11/3/2010", "dog", 3 }, { "11/3/2010", "cat", 8 } };

        HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();

        for (Object[] record : data) {
            Map<String, AnimalValCnt> innerMap = null;
            if ((innerMap = animalMap.get(record[0])) == null) {
                innerMap = new HashMap<String, AnimalValCnt>();
                animalMap.put((String) record[0], innerMap);
            }
            AnimalValCnt obj = null;
            if ((obj = innerMap.get(record[1])) == null) {
                obj = new AnimalValCnt();
                innerMap.put((String) record[1], obj);
            }
            obj.Sumval += (Integer) record[2];
            obj.cnt++;
        }
        System.out.println(animalMap);
    }

}

class AnimalValCnt {
    int Sumval;
    int cnt;

    @Override
    public String toString() {
        return "(" + Sumval + "," + cnt + ")";
    }
}

Once you have got the data in a map then it's easy to populate these data to a table.You can use a tablemodel for this purpose.Have a look at this code to understand how data from a map can be loaded into a table using TableModel.

UPDATE:

public class AnimalMapping {

        public static void main(String[] args) throws NumberFormatException, IOException {

            BufferedReader in = new BufferedReader(new FileReader("foo.in"));
            String line;
            String[] record;
            HashMap<String, Map<String, AnimalValCnt>> animalMap = new HashMap<String, Map<String, AnimalValCnt>>();

            while(((line = in.readLine()) != null)) {
                record=line.split("\\s+");
                Map<String, AnimalValCnt> innerMap = null;
                if ((innerMap = animalMap.get(record[0])) == null) {
                    innerMap = new HashMap<String, AnimalValCnt>();
                    animalMap.put(record[0], innerMap);
                }
                AnimalValCnt obj = null;
                if ((obj = innerMap.get(record[1])) == null) {
                    obj = new AnimalValCnt();
                    innerMap.put(record[1], obj);
                }
                obj.Sumval +=  Integer.valueOf(record[2]);
                obj.cnt++;
            }
            System.out.println(animalMap);
        }

    }

    class AnimalValCnt {
        int Sumval;
        int cnt;

        @Override
        public String toString() {
            return "(" + Sumval + "," + cnt + ")";
        }
    }

@Dilantha Chamal: Reading from file was already given by Box9.I just included it in my code.You should be putting some effort here.Maybe you are a beginner that's why I wrote the code.Now try to implement the TableModel by yourself.Just a friendly advice:unless you do it you are never going to learn.


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.io.LineProcessor;

public class AnimalSummaryBuilder
{
 private static final Splitter SPLITTER = Splitter.on(CharMatcher.anyOf(","));

 private static final Joiner JOINER = Joiner.on("\t");

 @SuppressWarnings("unchecked")
 public static void main(final String[] args) throws Exception
 {
  @SuppressWarnings("rawtypes")
  Map<Animal, Summary> result = Files.readLines(new File("c:/1.txt"), Charsets.ISO_8859_1, new LineProcessor() {

   private final Map<Animal, Summary> result = Maps.newHashMap();

   public Object getResult()
   {
    return result;
   }

   public boolean processLine(final String line) throws IOException
   {
    Iterator<String> columns = SPLITTER.split(line).iterator();

    String date = columns.next();
    String name = columns.next();
    int value = Integer.valueOf(columns.next()).intValue();

    Animal currentRow = new Animal(date, name);

    if (result.containsKey(currentRow))
    {
     Summary summary = result.get(currentRow);
     summary.increaseCount();
     summary.addToTotal(value);
    }
    else
    {
     Summary initialSummary = new Summary();
     initialSummary.setCount(1);
     initialSummary.setTotal(value);
     result.put(currentRow, initialSummary);
    }
    return true;
   }
  });

  for (Map.Entry<Animal, Summary> entry : result.entrySet())
  {
   Animal animal = entry.getKey();
   Summary summary = entry.getValue();
   System.out.println(JOINER.join(animal.date, animal.name, summary.total, summary.count));
  }
 }

 final static class Animal
 {
  String date;

  String name;

  public Animal(final String date, final String n)
  {
   this.date = date;
   this.name = n;
  }

  @Override
  public int hashCode()
  {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((date == null) ? 0 : date.hashCode());
   result = prime * result + ((name == null) ? 0 : name.hashCode());
   return result;
  }

  @Override
  public boolean equals(Object obj)
  {
   if (this == obj)
   {
    return true;
   }
   if (obj == null)
   {
    return false;
   }
   if (!(obj instanceof Animal))
   {
    return false;
   }
   Animal other = (Animal) obj;
   if (date == null)
   {
    if (other.date != null)
    {
     return false;
    }
   }
   else if (!date.equals(other.date))
   {
    return false;
   }
   if (name == null)
   {
    if (other.name != null)
    {
     return false;
    }
   }
   else if (!name.equals(other.name))
   {
    return false;
   }
   return true;
  }

 }

 final static class Summary
 {
  private int total;

  private int count;

  void setTotal(int value)
  {
   total = value;
  }

  void setCount(int i)
  {
   count = i;
  }

  void increaseCount()
  {
   count++;
  }

  void addToTotal(int valueToAdd)
  {
   total += valueToAdd;
  }
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜