I have a code that reads a multiple text files from a folder and I need to put them in a table.So far,everything is good except that every line from my text files are displayed in a different table.I know that the problem is that the table receives each line separately.I tried to create an object and fill it and then call inside the table but I couldn't make it work so if anyone can tell me the solution that would be great. Also I need to be able to compare the values and find an average,so if you have any tips for that to,would be great
here's an example of my text file
17/10/2012 10:00:06.67 [RX] - E usbR<LF>
817EE765FF53-53<LF>
817AA765FF53-34<LF>
817CC765FF53-25<LF>
00<LF>
E qEnd<LF>
and this is what I need to get in the table
ID RSSI
817EE765FF53 53
817AA765FF53 34
817CC765FF53 25
here is the code
import java.awt.BorderLayout;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class Foldersearch1
{
public static void main(String[] args)
{
// Directory path here
String path = "C:/Users/Nikica/Desktop/text files";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
System.out.println(files);
();
String currentLine="";
File textFile = new File(folder.getAbsolutePath() + File.separator + files);
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(textFile);
try (DataInputStream in = new DataInputStream(fstream)) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String line;
//Read File Line By Line
// int p=0;
// Object[][] Table=null;
while ((strLine = br.readLine()) != null) {
processLine(strLine);
Table(strLine);
// Print the content on the console
//System.out.println (strLine);
}
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
}
}
public static void processLine(String line) {
// skip header & footer
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) {return;}
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
System.out.println("ID [" + ID + "]\t RSSI [" + RSSI +"]");
}
public static void Table(String line) {
JFrame frame = new JFrame("proba");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
if (line.startsWith("17/10/2012 10:00:06.67 [RX] - E usbR<LF>") || line.startsWith("E qEnd<LF>")) return;
String ID = line.substring(0, 12);
String RSSI = line.substring(13, 15);
Object rowData[][] = { { ID, RSSI } };
Object columnNames[] = { "ID", "RSSI" };
JTable table = new JTable(rowData, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
To make your code work with minimal changes, Create a Vector with the rowdata, and use the constructor public JTable(Vector rowData, Vector columnNames). The following code snippet should give you an idea on how to do it.
Vector<String> columnNames = new Vector<String>();
columnNames.add("ID");
columnNames.add("RSSI");
Vector<Vector<String>> rowData = new Vector<Vector<String>>();
for(int i=0; i<20; i++) {
Vector<String> row = new Vector<String>();
row.add("ID_" + i);
row.add("RSSI_" + i);
rowData.add(row);
}
JTable table = new JTable(rowData, columnNames);
Related
I want to read a csv File and put words " Jakarta " and " Bandung " in a combobox. Here's the input
id,from,
1,Jakarta
2,Jakarta
5,Jakarta
6,Jakarta
10,Bandung
11,Bandung
12,Bandung
I managed to get the words and put it in the combobox, but as you can see, the text file itself contains a lot word " Jakarta " and " Bandung " while i want to show both only once in the combobox.
Here's my temporary code, which works for now but inefficient and probably can't be used if the word has more variety
public String location;
private void formWindowOpened(java.awt.event.WindowEvent evt) {
String csvFile = "C:\\Users\\USER\\Desktop\\Project Data.csv";
BufferedReader br = null;
LineNumberReader reader = null;
String line = "";
String cvsSplitBy = "-|\\,";
br = new BufferedReader(new FileReader(csvFile));
reader = new LineNumberReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bookingdata = line.split(cvsSplitBy);
location = bookingdata[1];
ComboBoxModel model = cmb1.getModel();
int size = model.getSize();
cmb1.addItem(location);
for(int i = 1; i < size; i++){
if(model.getElementAt(i).equals("from")){
cmb1.removeItemAt(i);
}
else if(model.getElementAt(i).equals("Bandung")){
cmb1.removeItemAt(i);
}
for(int j = 2; j < i; j++){
if(model.getElementAt(j).equals("Jakarta")){
cmb1.removeItemAt(j);
}
}
}
}
}
Someone else recommended this approach
boolean isEquals = false;
for(i = 0; i < a && !isEquals; i++){
isEquals = location.equals("Jakarta");
if(isEquals){
cmb1.addItem("Jakarta");
}
}
This code doesn't work. As the code doesn't stop once it adds a " Jakarta " but it stops after it completed a loop. thus it still creates duplicate within the combobox.
I would like to know if there's any other code i can try. Thank you
Try putting all the words in a Set first and then add it in the combobox. Set itself will take care of exact one occurrence of each word.
Something like this:
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bookingdata = line.split(cvsSplitBy);
location = bookingdata[1];
ComboBoxModel model = cmb1.getModel();
int size = model.getSize();
// add all location in set and set will only allow distinct values
locationSet.add(location);
}
// after looping through all location put it in combobox
for(String location:locationSet)cmb1.addItem(location);
}
}
As discussed in comments, Sets are meant to keep unique values. Please find the screenshot of JShell below:
PS: This is just to give an idea and may need some amendment as per requirement.
--EDITED--
As discussed, it seems you are still missing something, I tried and write below piece of code and worked fine
package com.digital.core;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(300, 300);
String data = "id,from,\n" +
"1,Jakarta\n" +
"2,Jakarta\n" +
"5,Jakarta\n" +
"6,Jakarta\n" +
"10,Bandung\n" +
"11,Bandung\n" +
"12,Bandung";
String[] dataArr = data.split("\n");
Set<String> locationSet = new HashSet<>();
for(String line:dataArr) {
locationSet.add(line.split(",")[1]);
}
JComboBox<String> comboBox = new JComboBox<>();
for(String location:locationSet)
comboBox.addItem(location);
jframe.add(comboBox);
jframe.setVisible(true);
}
}
You could create an ObservablArrayList of strings and as you read the CSV file, check if the list already contains that string:
ObservableList<String> locationsList = FXCollections.observableArrayList();
// Add your strings to the array as they're loaded, but check to
// make sure the string does not already exist
if (!locationsList.contains(location)) {
locationsList.add(location);
}
Then, after reading the whole file and populating the list, just set the items in your combobox to that ObservableArrayList.
I need to some help about JTable.I'm trying to read data from "Contact.txt" file and populate my table with that datas.I can get data from file correctly with adding to Object[][] 2D array without any problem.When I try to add this Object array to table not happens any thing.
Sorry for my bad English.
Contacts.txt file include "Name","LastName","Phone Num","Email" s.
And this Class read the text and add it to Object :
public class ReadFromText {
public boolean ReadTable(Object [][] data) {
boolean status = false;
File file = new File("/Users/MacbookPro/Documents/Contacts.txt");
BufferedReader bf = null;
FileReader fileReader = null;
try {
fileReader = new FileReader(file);
bf = new BufferedReader(fileReader);
String textLine = null;
String [] text = null;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < 4; j++) {
while ((textLine = bf.readLine()) != null) {
text = textLine.split(" ");
data[i][j] = text[j];
status = true;
System.out.println(data[i][j]);
}
}
}
bf.close();
} catch (IOException e) {
System.err.println(e.getMessage());
}
return status;
}
}
This part of code from main Class :
Object [][]datas = new Object[10][4];
ReadFromText r = new ReadFromText(); //new object from ReadData class
if(r.ReadTable(datas)== true){
System.out.println("OK");//just for to be sure
}else{
System.out.println("NO");
}
model = new DefaultTableModel(datas, columNames);
table = new JTable(model);
table.setFont(new Font("Monospaced", Font.PLAIN, 13));
table.setBackground(new Color(245, 245, 245));
table.setRowHeight(25);
table.setMinimumSize(new Dimension(60, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
It' return "OK" check it from here
But JTable is empty !!! : look it from this picture
I hope to anyone can help me.THANKS FOR ALL
Your code to read the data from the file is wrong. Think about it for a minute. You start the outer loop with a value of 0, then you have you inner loop with a value of 0 and then you read the entire file using the while loop.
You want your logic to read a single line of data, split that line and add then add the data to the array. So the logic should be something like:
int row = 0;
while ((String textLine = bf.readLine()) != null)
{
String text = textLine.split(" ");
for (int i = 0; i < text.length; i++)
{
data[row][i] = text[i];
}
row++
}
However, you should NOT be using Arrays to hold the data. You should never hardcode the size of a data structure since it does not allow you to add new data. Instead you should be using a Vector to read the data. Then it doesn't matter is you have 10 rows of data or 100.
Using this approach the code would be something like:
Vector data = new Vector();
while ((String textLine = bf.readLine()) != null)
{
String text = textLine.split(" ");
Vector row = new Vector();
for (int i = 0; i < text.length; i++)
{
row.addElement( text[i] );
}
}
So you would need to change the method to return the Vector of data. You would also need to change your "columnNames" to be added to a Vector so you can create the TableModel using the two Vectors.
I hope this answer will help you find the problem. It is also meant to demonstrate the importance of posting an MCVE, like the following:
mport java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestTable extends JFrame {
public TestTable() {
super("Main");
setSize(400, 300);
Object [][]datas = new Object[][]{
{"A1", "A2","A3","A4"},
{"B1", "B2","B3","B4"}
};
Object[] columNames = {"Name","LastName","Phone Num","Email"};
DefaultTableModel model = new DefaultTableModel(datas, columNames );
JTable table = new JTable(model);
table.setBackground(new Color(245, 245, 245));
table.setRowHeight(25);
table.setMinimumSize(new Dimension(60, 20));
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
add(new JScrollPane(table));
setVisible(true);
}
public static void main(String[] args) {
new TestTable();
}
}
Not only an MCVE helps you get better and faster response, in many cases, like this one, it helps you pin point the problem and solve it by yourself.
Removing everything that is not essential to reproduce the problem, help you (and who ever tries to help) focus on where the problem is.
In this case you can see that eliminating the input part, you can see that the JTable works fine.
I'm having stuck at reading back from csv wheres i'm success at creating the csv.
the problem I'm facing is I cant get a clue on how to obtain the values getting from csv back to the jTable.
I'm not having any other problems aside from public void fromCsv
class FCMS extends JFrame{
String header[] = {"Firstname","Lastname","FCMS ID","Email"};
String data[][];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
JPanel pane = new JPanel();
JPanel pane_input = new JPanel();
JLabel lbl_firstname = new JLabel(" Firstname");
JLabel lbl_lastname = new JLabel(" Lastname");
JLabel lbl_id = new JLabel(" FCMS ID");
JLabel lbl_email = new JLabel(" Email");
JTextField txt_firstname = new JTextField(10);
JTextField txt_lastname = new JTextField(10);
JTextField txt_id = new JTextField(10);
JTextField txt_email = new JTextField(10);
JButton btn_add = new JButton("Add Entry");
JButton btn_Csv = new JButton("Export to Csv");
JButton btn_load = new JButton("Load From Csv");
public FCMS(){
setSize(200,200);
setPreferredSize(new Dimension(350,300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
setTitle("Flight Crew Management System");
btn_add.setMnemonic(KeyEvent.VK_A);
btn_Csv.setMnemonic(KeyEvent.VK_E);
btn_load.setMnemonic(KeyEvent.VK_L);
pane_input.setLayout(new GridLayout(0,2));
pane_input.add(lbl_firstname);
pane_input.add(txt_firstname);
pane_input.add(lbl_lastname);
pane_input.add(txt_lastname);
pane_input.add(lbl_id);
pane_input.add(txt_id);
pane_input.add(lbl_email);
pane_input.add(txt_email);
pane_input.add(btn_add);
pane_input.add(btn_Csv);
pane_input.add(btn_load);
pane.setLayout(new BorderLayout());
pane.add(pane_input, BorderLayout.NORTH);
pane.add(new JScrollPane(table), BorderLayout.CENTER);
add(pane);
pack();
setVisible(true);
btn_add.addActionListener(new AksyonListener());
btn_Csv.addActionListener(new AksyonListener());
btn_load.addActionListener(new AksyonListener());
txt_email.addActionListener(new AksyonListener());
}
public void toCsv(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter Csv = new FileWriter(file);
for(int i = 0; i < model.getColumnCount(); i++){
Csv.write(model.getColumnName(i) + ",");
}
Csv.write("\n");
for(int i=0; i< model.getRowCount(); i++) {
for(int j=0; j < model.getColumnCount(); j++) {
Csv.write(model.getValueAt(i,j).toString()+",");
}
Csv.write("\n");
}
Csv.close();
}catch(IOException e){ System.out.println(e); }
}
public void fromCsv(File file){
BufferedReader fileReader = null;
model.setRowCount(0);
try{
//Create the file reader
fileReader = new BufferedReader(new FileReader(file));
//Read the CSV file header to skip it
fileReader.readLine();
int fn = 0;
int ln = 1;
int id = 2;
int email = 3;
String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {
// }
}
/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/
fileReader.close();
}catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
}
}
public static void main(String[] args){
new FCMS();
}
class AksyonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == btn_add || e.getSource() == txt_email){
String fn = txt_firstname.getText();
String ln = txt_lastname.getText();
String id = txt_id.getText();
String mail = txt_email.getText();
txt_firstname.setText("");
txt_lastname.setText("");
txt_id.setText("");
txt_email.setText("");
txt_firstname.requestFocus();
model.insertRow(model.getRowCount(), new Object[]{fn, ln, id, mail});
}
else if(e.getSource() == btn_Csv){
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(FCMS.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
toCsv(table, new File(file));
}
}
else if(e.getSource() == btn_load){
JFileChooser fc = new JFileChooser();
int option = fc.showOpenDialog(FCMS.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
fromCsv(new File(file));
}
}
}
}
}
Problem is solved:
try{
//Create the file reader
fileReader = new BufferedReader(new FileReader(file));
//Read the CSV file header to skip it
fileReader.readLine();
int fn = 0;
int ln = 1;
int id = 2;
int email = 3;
String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {
// }
}
/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/
fileReader.close();
}
String[] tokens = line.split(",");
Above is where you split one line of data into an array, so above is where you then need to take the data from the array and add it to the TableModel.
So your code should be:
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
Then there is no need for the second loop.
However, the above code will just append data to the existing "model", so you may also need to clear all the data in the model. You can do this by adding:
model.setRowCount(0);
before the loop.
I am very new to java. I am working on project for class that would look up books in a text file and display information about them. Primarily if the book is in stock or not. The text file is set up like this: {ISBN, Author, Type, Stock}
I have coded a user interface that allows the user to type in ISBN, Author, and Type. Ideally, I would like for the user to just search one of these and return the needed information. However, just searching via ISBN would be acceptable for now. My code right now only takes what is typed into the textboxes and displays it in a large textbox. I am somewhat familiar with reading a text file in but have no idea how I would take the text from a textbox and use it to search the file. Any help would be greatly appreciated.
Here is my code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
public class InventoryInterface extends JFrame
{
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 350;
private JButton btnSearch;
private JButton btnDatabase;
private JButton btnRefresh;
private JLabel lblISBN, lblAuthor, lblType;
private JTextField txtISBN, txtAuthor, txtType;
private JTextArea txtOutput;
public InventoryInterfaceSimple()
{
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createComponents()
{
btnSearch = new JButton("Search");
lblISBN = new JLabel("ISBN");
lblAuthor = new JLabel("Author");
lblType = new JLabel("Type");
txtISBN = new JTextField(10);
txtAuthor = new JTextField(10);
txtType = new JTextField(10);
txtOutput = new JTextArea(30,30);
txtOutput.setText("");
txtOutput.setEditable(false);
ActionListener action = new InventoryOutput();
btnSearch.addActionListener(action);
JPanel panel = new JPanel();
panel.setLayout(null);
lblISBN.setBounds(10,10,50,25);
txtISBN.setBounds(55,10,125,25);
lblAuthor.setBounds(10,40,50,25);
txtAuthor.setBounds(55,40,125,25);
lblType.setBounds(10,70,50,25);
txtType.setBounds(55,70,125,25);
btnSearch.setBounds(30,130,150,25);
JScrollPane scrollArea = new JScrollPane(txtOutput);
scrollArea.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollArea.setBounds(200,10,350,200);
panel.add(scrollArea);
panel.add(lblISBN);
panel.add(txtISBN);
panel.add(lblAuthor);
panel.add(txtAuthor);
panel.add(lblType);
panel.add(txtType);
panel.add(btnSearch);
panel.add(scrollArea);
add(panel);
}
class InventoryOutput implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String inventoryString = "";
inventoryString += txtISBN.getText() + " - ";
inventoryString += "Author: " + txtAuthor.getText() + " - ";
inventoryString += "Type: " + txtType.getText() + " - ";
txtOutput.append(inventoryString + "\n");
txtISBN.setText("");
txtAuthor.setText("");
txtType.setText("");
}
}
}
you can replace your code with this.. this is a starting point, you can do many improvements to this code, but this will work. change REPOSITORY_FILE_PATH to your data file
class InventoryOutput implements ActionListener {
private final String REPOSITORY_FILE_PATH = "C:\\temp\\book-repo.txt";
private final File REPOSITORY_FILE = new File(REPOSITORY_FILE_PATH);
public void actionPerformed(ActionEvent event) {
String inventoryString = "";
String requestedISBN = txtISBN.getText().trim().toLowerCase();
String requestedAuthor = txtAuthor.getText().trim();
String requestedType = txtType.getText().trim();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(REPOSITORY_FILE));
String line;
while ((line = reader.readLine()) != null) {
String lineLtrim = line.toLowerCase().replaceAll("^\\{", ""); //{
String lineRtrim = lineLtrim.replaceAll("\\}$", ""); //}
String[] data = lineRtrim.split(","); //ISBN, Author, Type, Stock
if (data.length < 4) {
throw new IllegalArgumentException("bad datafile: All fields must be entered: " + line);
}
if (data[0].equals(requestedISBN)) {
inventoryString += txtISBN.getText() + " - Author: " + data[1] + " - Type: " + data[2] + " - Stock:" + data[3];
txtOutput.append(inventoryString + "\n");
return;
}
}
reader.close();
inventoryString += txtISBN.getText() + " - Not Found";
txtOutput.append(inventoryString + "\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
you can just add this main() code to test, ideally you should write unit test-- to cover all cases.
public static void main(String[] args) {
JFrame f = new InventoryInterface();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setPreferredSize(new Dimension(600, 600));
f.pack();
f.setVisible(true);
}
data file
{ISBN1234,me,drama,5}
{ISBN1235,me,Tech,0}
{ISBN1236,me,Fiction,2}
{ISBN1237,me,Audio/Kids,4}
Not sure which part you did not get,,
on the listener-- we read the ISBN entered by user String
requestedISBN = txtISBN.getText().trim().toLowerCase(); and convert
it in lower case so, we can compare with lower-cased-data
then we read your data file (line by line)
we then from each line we remove character "{" and "}" // comment
says that
then we get "isbn,author, type, stock" , so we split by ","
split gives us array of string putting each element in array in
order i.e data[0] has isbn, data[1] has author ...etc
we check if the data file is correct by making sure we have all
elements in there i.e if (data.length < 4) {
we throw exception if the size of array is not <4 i.e. we found that
the data file has incorrect data.
then we compare if the input isbn (data[0]) is same as one of the
line element from your data file
if we find a match we display it in the textArea and exit the loop,
if we dont find we display "not Found"
If you wrote the code (listener) yourself, this should be trivial to you.
You could create a private String chosenISBN and set the value of it in the actionPerformed method. Then you can access the value everywhere in the class.
You could even create a getter for the chosenISBN as well, if you need it.
here i am trying to use Buffered reader to read text file and create table in database, but Buffered reader reads only First Name from my text file. May i know What is wrong in my code... It WORKS Fine In MySQL , but in SQL Server it reads only first name.
Text File: http://textuploader.com/?p=6&id=vrQs9
Whole Code :
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.DatabaseMetaData;
import com.mysql.jdbc.Statement;
import java.io.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class Stackq extends AbstractTableModel {
Vector<String> data;
Vector columns;
public Stackq() {
String line;
data = new Vector<String>();
columns = new Vector();
int count = 0;
try {
FileInputStream fis = new FileInputStream("D:/joy/text/registration.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), "\t");
while (st1.hasMoreTokens()) {
columns.addElement(st1.nextToken());
count++;
}
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "\t");
for (int i = 0; i < count; i++) {
if (st2.hasMoreTokens()) {
data.addElement(st2.nextToken());
} else {
data.addElement("");
}
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setValueAt(Object value, int row, int col) {
data.setElementAt((String) value, col);
fireTableCellUpdated(row, col);
}
public boolean isCellEditable(int row, int col) {
//if (4 == col){
return true;
}
//else {
// return false;
// }
//}
//public void insertData(Object[] values){
// data.add(new Vector());
//for(int i =0; i<values.length; i++){
//((Vector) data.get(data.size()-1)).add(values[i]);
//}
//fireTableDataChanged();
// }
public void removeRow(int row) {
data.removeElementAt(row);
fireTableDataChanged();
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return columns.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
public String getColumnName(int i) {
return (String) columns.get(i);
}
public static void main(String args[]) {
Stackq model = new Stackq();
JTable table = new JTable();
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
JPanel panel = new JPanel();
panel.add(scrollpane);
JFrame frame = new JFrame();
frame.add(panel, "Center");
frame.pack();
frame.setVisible(true);
StringBuffer sbTableData = new StringBuffer();
for (int row = 0; row < table.getRowCount(); row++) {
for (int column = 0; column < table.getColumnCount(); column++) {
sbTableData.append(table.getValueAt(row, column)).append("\t");
}
sbTableData.append("\n");
}
System.out.println(sbTableData);
try {
PrintWriter f = new PrintWriter(new BufferedWriter(new FileWriter("D:/joy/text/registration6.txt", true)));
//f.println(sbTableData+"\t"+"n");
f.close();
} catch (IOException e) {
e.printStackTrace();
}
String readstr1 = null;
int row = table.getRowCount();
int column = table.getColumnCount();
for (int j = 0; j < row; j++) {
for (int i = 0; i < column; i++) {
//System.out.println(table.getValueAt(j, i));
readstr1 = (String) table.getValueAt(j, i);
//System.out.println(readstr);
}
}
try {
// FILE READ AND TABLE CREATE
String tname = "example11199";
String dbname = "DB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;user=SOFTWARE\joy;databaseName=DB;integratedSecurity=true;");
java.sql.Statement stmt = conn.createStatement();
// stmt=conn.createStatement();
//System.out.println("connect");
//System.out.println(readstr1);
FileInputStream fstr = new FileInputStream("D:/joy/text/registration6.txt");
// Get the object of DataInputStream
DataInputStream inn = new DataInputStream(fstr);
BufferedReader brr = new BufferedReader(new InputStreamReader(inn));
String readstr;
java.sql.DatabaseMetaData dmd = conn.getMetaData();
while ((readstr = brr.readLine()) != null) //DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
//while(readstr!=null)
{
ResultSet rs = dmd.getTables(null, "DB", "example11199", null);
//set not null column
if (String.valueOf(readstr).contains("NO")) {
readstr = readstr.replaceAll("NO", "not null");
} else if (String.valueOf(readstr).contains("YES")) {
readstr = readstr.replaceAll("YES", "");
}
if (String.valueOf(readstr).contains("PRIMARY")) {
readstr = readstr.replaceFirst("PRIMARY", "primary key");
}
System.out.println("replace string " + readstr);
int k = 1;
if (!rs.next()) {
stmt.executeUpdate("CREATE TABLE " + tname + "(" + readstr + ")");
} else {
//System.out.println(readstr);
stmt.executeUpdate("ALTER TABLE " + tname + " ADD(" + readstr + ")");
System.out.println("altered");
}
}
brr.close();
inn.close();
} catch (Exception e) {
}
}
}
EDITED, Now all contents of text file gets printed but it gives null here at last : System.out.println("replace string " + readstr); so i am unalble to create table with null value.
Thank You.
You are re-creating the table you read one line. I assume this only works once, so it is only reading the first line.
You appear to have a jumble of text passing and altering a table so that only the file line is read before you attempt to create the table. I suspect you want to read the whole file before you attempt to alter/create the table.
BTW Having formatting all over the place is likely to make checking your code much harder. I suggest you use the formatter in your IDE and you should be able to see how your code will loop.
while ((readstr = brr.readLine()) != null) //DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
//while(readstr!=null)
{
ResultSet rs = dmd.getTables(null, "DB", "example11199", null);
//set not null column
if (String.valueOf(readstr).contains("NO")) {
readstr = readstr.replaceAll("NO", "not null");
} else if (String.valueOf(readstr).contains("YES")) {
readstr = readstr.replaceAll("YES", "");
}else if (String.valueOf(readstr).contains("PRIMARY")) {
readstr = readstr.replaceFirst("PRIMARY", "primary key");
}
System.out.println("replace string " + readstr);
Try to fix the last if statement Check it again and it will Work.