populate a 'JTable' with values from a text file [duplicate] - java

This question already has an answer here:
populate a 'JTable' with values from a '.txt' file
(1 answer)
Closed 7 years ago.
I have a text file like this
0786160384|P. K.|Tharindu|912921549v|Colombo|
0711495765|P. K.|Gamini|657414589v|Colombo|
0114756199|H. P.|Weerasigha|657895478v|Kandy|
each |separates a data. I want to display the data on this file in a jTable. below is my code so far.
public class PrintGUI extends javax.swing.JFrame {
File file, tempFile;
FileReader fileReader;
FileWriter fileWriter;
ArrayList ClientList;
Vector data = new Vector();
Vector columns = new Vector();
public PrintGUI() {
initComponents();
this.setIconImage(new ImageIcon(getClass().getResource("/Images/icon.png")).getImage());
file = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\phonebook.txt");
tempFile = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\tempphonebook.txt");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
PhoneBookTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Phone No", "First Name", "Last Name", "NIC", "City"
}
)
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
String line = null;
DefaultTableModel dtm = (DefaultTableModel) PhoneBookTable.getModel();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
StringTokenizer st1 = new StringTokenizer(br.readLine(), "|");
while (st1.hasMoreTokens()) {
columns.addElement(st1.nextToken());
}
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "|");
while (st2.hasMoreTokens()) {
data.addElement(st2.nextToken());
}
}
br.close();
dtm.addRow(new Object[]{columns, data});
} catch (Exception e) {
e.printStackTrace();
}
}
problem is when I run the program it shows a whole line on text from the .txt file instead of a single data per column.
more specifically it shows the whole line of
[0786160384, P. K., Tharindu, 912921549v, Colombo]
in the first row first column and
[0711495765, P. K., Gamini, 657414589v, Colombo, 0114756199, H. P., Weerasigha, 657895478v, Kandy]
in the first row second column
Instead I want it to display single data per cell. can some one please help?

You only call addRow once, so of course there will be only one row added to the table model.
You need to move that statement inside your file-reading loop.
Each line you read from the file corresponds to a row in your table. As such, you need to call addRow each time you have read a line, and call it with the contents of that line.

Finally found the error. It should be like
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
data = new Vector();// this is important
StringTokenizer st1 = new StringTokenizer(line, "|");
while (st1.hasMoreTokens()) {
String nextToken = st1.nextToken();
data.add(nextToken);
System.out.println(nextToken);
}
System.out.println(data);
dtm.addRow(data);//add here
System.out.println(".................................");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Expanding abbreviations from .csv file

So I have this task to do, I need to expand text abbreviations from the message into their full form from the .csv file, I loaded that file into HashMap, with keys as abbreviations and values as full forms. There is a loop to iterate through the keys and if statement which replaces abbreviation to full form if it finds any. I kind of figured it out and it is working as it should but I want to send this changed String (with abbreviations expanded) somewhere else out of if statement to save the full message to the file. I know that this String exists only in this if statement but maybe there is another way of doing it? Or maybe I'm doing something wrong? I became a bit rusty with Java so maybe there is a simple explanation that I don't know about. Here is the code I have :
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
//read the .csv file
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
for (String key : list.keySet()) {
//if any abbreviations found then replace them with expanded version
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");
try {
File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
} catch (IOException f) {
f.printStackTrace();
}
}
}
Not sure I understood well your problem. But I think you should separate the different steps in your code.
I mean your try-catch block that writes your output should be outside the for-loop and outside the reading try-catch. And your for-loop should be outside your reading try-catch.
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
//read the .csv file
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//if any abbreviations found then replace them with expanded version
for (String key : list.keySet()) {
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");
}
}
//output the result in your file
try {
File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Displaying data in JTable while reading the data from the text file

I'm trying to display the column data from separate file and row data from another but it's output is not in normal for row file below attached is the image file for output and both the text file:
private void orbuttonActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) orderitemtable.getModel();
model.setRowCount(0);
String filename = "ORDERITEMFILE.txt";
String idnamefile = "odcofile.txt";
File file1 = new File(idnamefile);
File file = new File(filename);
try {
BufferedReader br = new BufferedReader(new FileReader(file1));
BufferedReader br1 = new BufferedReader(new FileReader(file));
//to make the columns name so to get the first line of code
//set columnsname to the jtable Model
String firstLine = br.readLine().trim();
String[] columnsName = firstLine.split("/");
model.setColumnIdentifiers(columnsName);
//get lines from txt files
Object[] tablelines = br1.lines().toArray();
//Extracting the data from lines
//set data to jtable Model
for (int i = 0; i < tablelines.length; i++) {
String line = tablelines[i].toString().trim();
String[] dataRow = line.split(",");
model.addRow(dataRow);
}
} catch (Exception ex) {
Logger.getLogger(productpage.class.getName()).log(Level.SEVERE, null, ex);
}
}
The problem is its displaying the column's until product type after that it changes to new row and display the rest of content over there:
This is the text file for row it read's properly from the txt file the only problem is when it display in JTable it read's in separate row for the last two quantities.
This is the text file for column which.
First off, you really don't need a single file to hold Column Names. You can apply the Column Names as the very first line of your ORDERITEMFILE.txt file, very much like a CSV file would be laid out. Generally the first line of a CSV file would be a delimited string of the Column Names and it's there to be specifically used as such.
If you insist on utilizing two files then may I suggest you deal with the Column Names file first and be rid of it so that it doesn't clutter things up within your event code. Perhaps do this in a separate method:
private String[] getColumnNames(String filePath) {
String[] columns = {};
//Try with Resources (auto closes the reader)
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
// Assumes there is only one line in file.
while ((line = br.readLine()) != null) {
// Ignore blank lines (if any) leading to the line we want.
if (!line.equals("")) { break; }
}
if (line != null && !line.equals("")) {
columns = line.split("/");
}
}
catch (FileNotFoundException ex) {
System.err.println("Column Names File Not Found!");
}
catch (IOException ex) {
System.err.println("IO Exception Encounterd!\n" + ex.getMessage());
}
return columns;
}
Holding the thought of keeping things organized to some degree we now can have another method to set the new Column Names to JTable:
private void setTableColumns(JTable table, String[] columnsName) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setColumnIdentifiers(columnsName);
}
And still holding the organizational thought we have yet another method to fill the JTable with file data:
private int fillTableFromFile(JTable table, String filePath) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int recordCount = 0;
//Try with Resources (auto closes the reader)
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
// Clear current table rows
while (model.getRowCount() > 0) {
for (int i = 0; i < model.getRowCount(); i++) {
model.removeRow(i);
}
}
String dataLine;
Object[] dataArray;
// read in the data and add to table.
while ((dataLine = br.readLine()) != null) {
// Ignore blank lines (if any).
if (dataLine.equals("")) { continue; }
//Split the comma delimited data line into a Object Array
dataArray = dataLine.split(",");
model.addRow(dataArray);
recordCount++;
}
}
catch (FileNotFoundException ex) {
System.err.println("Data File Not Found!");
}
catch (IOException ex) {
System.err.println("IO Exception Encounterd!\n" + ex.getMessage());
}
return recordCount; // The number of records added to table from file.
}
With the above methods in place you can now have some 'easy to follow' (and controllable) code within your JButton Action Performed event. By controllable, I mean for example, you can determine what is to happen if (for whatever reason) the coloumnsName String Array is empty or null (not handled here):
private void orbuttonActionPerformed(java.awt.event.ActionEvent evt) {
String filename="ORDERITEMFILE.txt";
String idnamefile="odcofile.txt";
String[] columnsName = getColumnNames(idnamefile);
setTableColumns(orderitemtable, columnsName);
int numOfRecords = fillTableFromFile(orderitemtable, filename);
JOptionPane.showMessageDialog(orderitemtable, "There were " + numOfRecords +
" Records Added to Table.", "Records Added",
JOptionPane.INFORMATION_MESSAGE);
}
When run and the Order Button is selected the table columns names will be placed, the table will be filled with file data, and a Message Box will appear indicating how many file records were added to table.

Need Advice on How To Set ComboBox and JXDatePicker back to original setting after clearing screen

I have a jpanel with some textfields, comboboxes, and jxdatepickers and a table which holds the values to those fields. Now, I want to select a row from the table and edit the values by repopulating them in order to change them. I have the following code for when I click the "edit" button after I have selected a row:
private void jButton_editActionPerformed(java.awt.event.ActionEvent evt) {
File h = new File("caseInfoTemp.txt");
BufferedWriter buf;
try {
buf = new BufferedWriter(new FileWriter(h, true));
int row = jTable_caseInfo.getSelectedRow();
for(int j = 0; j < jTable_caseInfo.getColumnCount(); j++) {
buf.write(jTable_caseInfo.getValueAt(row, j).toString() + "\t");
}
buf.newLine();
buf.close();
}catch (Exception e){
}
try{
FileInputStream fstream = new FileInputStream("caseInfoTemp.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
String[] delims = line.split("\t");
jSpinner_case.setValue(Integer.parseInt(delims[0]));
jTextField_case.setText(delims[1]);
//fix to set combobox to what was chosen
jComboBox_client.setPopupVisible(true);
//fix to set datepicker to what was chosen
jXDatePicker_openDate.setDate(null);
}
}catch (IOException | NumberFormatException e) {
}
}
I have the //comment lines explaining what I would like to do, but I do not know which option to select to get the "string" values from the text file to populate the comboboxes and the jxdatepicker fields. I can only get the textfields to populate correctly. Any advice would be much appreciated.
This is what I have found to work:
jComboBox_client.setSelectedItem(delims[2]);
now I just need to find the right way to setDate of jxdatepicker back to date picked.

How to load text data into a table using Java

I have a text data like
name = abc
id = 123
Place = xyz
Details = some texts with two line
name = aaa
id = 54657
Place = dfd
Details = some texts with some lines
I need to place them in a table or csv and my output should look like
name id Place Details
abc 123 xyz Some texts
dfd 54657 dfd Some texts
How can I do this with java?
Code for the CSV version :) It reads the input file and create a CSV in the format you asked for:
try {
BufferedReader sc = new BufferedReader(new FileReader("input2.txt"));
ArrayList<String> name = new ArrayList<>();
ArrayList<String> id = new ArrayList<>();
ArrayList<String> place = new ArrayList<>();
ArrayList<String> details = new ArrayList<>();
String line = null;
while ((line = sc.readLine()) !=null) {
if (!line.trim().equals("")) {
System.out.println(line);
if (line.toLowerCase().contains("name")) {
name.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("id")) {
id.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("location")) {
place.add(line.split("=")[1].trim());
}
if (line.toLowerCase().contains("details")) {
details.add(line.split("=")[1].trim());
}
}
}
PrintWriter pr = new PrintWriter(new File("out.csv"));
pr.println("name;id;Place;Details;");
for (int i = 0; i < name.size(); i++) {
pr.println(name.get(i) + ";" + id.get(i) + ";" + place.get(i) + ";" + details.get(i) + ";");
}
pr.close();
} catch (Exception e) {
e.printStackTrace();
}
Sample file content it processes:
name = abinhav
Location =Bangalore
Id =613636064725610496
Details = infoodnetwork: Q2 is up. You can still join the Megakitchens in India contest and grab some exciting vouchers. RT if you are enjoying…
name = Mathi
Location =Chennai
Id =613636066474508289
Details = i am the drifter Of course they can, but the BBC needs a daily negative story on India.
Reading from text file and writing to csv(comma seperated values) can be achieved using java io.
your logic should once write the headers to a text file with separator as comma and then read the corresponding values from the text may be use split("=") and append to the file with comma separator. You can create new files write the values and save the file with csv extension
try {
BufferedReader bReader = new BufferedReader(new FileReader("input file"));
String line = "";
while ((line = bReader.readLine()) != null) {
String[] strArray = line.split("=");
// write this to file
System.out.println( strArray[1]);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Parse the text file with a Scanner (doc here)
Create a DefaultTableModel (doc here). DefaultTableModel model = new DefaultTableModel(data, new String[]{"name","id","Place","Details"});, where data is a 2D String array with your data.
Create a JTable (doc here) with the model you just created. JTable table = new JTable(model);
Add the table to a JPanel, or JFrame, with a JScrollPane (if needed): panel.add(new JScrollPane(table));.

Populate a JList from a .txt reading line by line

I want to populate a JList from a .txt
I can't populate the JList...
Here's the code:
The .txt is formatted like this sample:
name1
name2
name3
The JList is declared in this way:
private javax.swing.JList jList1
This is the method used to read line by line:
private void visualizzaRosa(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
fileSquadra = squadra.getText();
try {
FileInputStream fstream = new FileInputStream("C:/Users/Franky/Documents....");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
Jlist1.add(strline); //to populate jlist
System.out.println(strLine); //to print on consolle
}
in.close();
} catch (Exception e) {
}
}
Thanks
Try
DefaultListModel listModel = new DefaultListModel();
while ((strLine = br.readLine()) != null)
{
listModel.addElement(strline);
System.out.println(strLine);
}
jList1.setModel(listModel);
and if i want to populate a Jtextarea instead of the jlist ????
Then use the read() method that is part of the API. THere is no need to write custom code:
textArea.read(...);

Categories

Resources