哎
我的文本文件如下所示
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
我每个月都有这种文本文件。上图显示了文本文件的一部分。所以我想用java到Jtable阅读这篇文章。
我已经使用StringTokanizer和Arreaylist来终止这个。不幸的是我做不到。 SO PLS帮助我........
所以我希望使用java程序将结果发送到jTable
日期 动物 总计 计数
11/2/2010 cat 20 3
11/3/2010 cat 9 2
答案 0 :(得分:2)
您不需要StringTokenizer(事实上,it's not recommended)。只需使用BufferedReader逐行获取输入,然后进行字符串拆分:
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"});
答案 1 :(得分:1)
测试:http://crysol.org/es/node/819
或
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
}
}
}
答案 2 :(得分:0)
您必须将数据填充到给定文件中的地图。我将举例说明如何填充数据。
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 + ")";
}
}
一旦你在地图中获得了数据,就可以很容易地将这些数据填充到一个表中。你可以使用tablemodel来实现这个目的。看看this code以了解地图中的数据是如何形成的。使用TableModel加载到表中。
<强>更新强>
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:Box9已经从文件中读取了。我只是将它包含在我的代码中。你应该在这里付出一些努力。也许你是初学者,这就是我编写代码的原因。现在试试自己实现TableModel。只是一个友好的建议:除非你这样做,否则你永远不会学习。
答案 3 :(得分:0)
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;
}
}
}