I wrote the program to create file and add in field using by jframe but it not working correctly, please help me thanks!!
read file get field full name and customer number and add one more field using jframe
full name and customer number working fine but jframe not working correctly.. so please help me...
and actually I need verticall scroll down as well, please help me..
suppose is there a 6 records in files in..
i need to put in jframe:
00240000844928953504
00240000844928953505
00240000844928953506
00240000844928953507
00240000844928953508
00240000844928953509
file output is not correct actually it put all 6 scanner line in all lines file out..
custID,fullname, 00240000844928953504
00240000844928953505
00240000844928953506
00240000844928953507
00240000844928953508
00240000844928953509
custID,fullname, 00240000844928953504
00240000844928953505
00240000844928953506
00240000844928953507
00240000844928953508
00240000844928953509
it like this!!:(
it should be like this!!
custID,fullname,00240000844928953504
custID,fullname,00240000844928953505
....
HEre is my code!!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class scanner {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final JFrame frame = new JFrame("Scan Here: ");
JPanel panel = new JPanel();
final JTextArea text = new JTextArea(20, 40);
JButton button = new JButton("Enter");
frame.add(panel);
panel.add(text);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
BufferedWriter lbwp = null;
String scanner = (text.getText());
System.out.println(scanner);
try {
File folderall = new File("FilesIn");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
String str = file.getName();
String reprintbwletterbwpca = ("FileOut" + "\\" + str);
lbwp = new BufferedWriter(new FileWriter(reprintbwletterbwpca));
lbwp.write("\"CUSTID\",\"FullName\",\"ONECODE\"," + "\n");
br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] actionID = line.split("\\\",\"");
String custnumber = actionID[3];
String fullname = actionID[18];
String add1 = actionID[19];
lbwp.write("\"" + custnumber + "\",\"" + fullname+ "\"," + "\"" + scanner + "\"," + "\n");
}
lbwp.close();
}
} catch(Exception e1) {
e1.printStackTrace();
}
frame.dispose();
}});
frame.setSize(500, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Please help me!!
Here you have two lists :
A list of entries coming from the file you are reading, each entry is read in "line" String.
A list of values you have input in a JTextArea separated by "\n".
First of all, you propably need to check if you have the same number of entries in the both lists. You also need to split your String scanner using "\n" as the separator.
As you are reading line by line, you can also use the following code which won't check if the number of entries are equals :
int index = 0;
String[] ids = scanner.split("\n");
while ((line = br.readLine()) != null) {
String[] actionID = line.split("\\\",\"");
String custnumber = actionID[3];
String fullname = actionID[18];
String add1 = actionID[19];
if (ids.length > index) {
lbwp.write("\"" + custnumber + "\",\"" + fullname+ "\"," + "\"" + ids[index] + "\"," + "\n");
} else {
lbwp.write("\"" + custnumber + "\",\"" + fullname+ "\"\n");
}
index++;
}
EDIT: replace the condition
Related
This question is similar to this : How do you reference a button inside of its actionlistener?
I want to create a simple form containing 8 toggle buttons. if i select the toggle button and click save button, it will write into the text file i.e "Button x, On". Next time i open the form, the form will check in the notepad if Button x is already on. If on, the toggle button will already be selected and vice versa.
I know how to write to and read from the notepad, but i am not sure how to check if i.e the user select button 2 then the code will write into second line " Button2, on"
Here is my code so far to write :
Path path = Paths.get(csvFile);
// check if button x is selected, if yes : <- how to refer to button x ?
BufferedWriter bw = new BufferedWriter(New FileWriter(csvFile, true);
writer.write ("button x,on" + "\r\n");
writer.close
and this is my code when the form is opened :
BufferedReader br = null;
String line = "";
String resFilesplitby = ",";
br = new BufferedReader(new FileReader(csvFile));
while((line = br.readLine()) != null){
String[] condition = line.split(csvFilesplitby);
String power = condition[1];
// check if button x is already selected
if (button x power.equals("on")){
button x.isSelected();
}
}
I manage to found a simple way to solve the problem
By adding the button to an array.
JToggleButton[] buttons = new JToggleButton[8];
buttons[0] = seat1; //this is variable name of my button.
buttons[1] = seat2;
buttons[2] = seat3;
buttons[3] = seat4;
buttons[4] = seat5;
buttons[5] = seat6;
buttons[6] = seat7;
buttons[7] = seat8;
// do the work here
for (JToggleButton btn : buttons){
if(btn.isSelected){
}
}
For simplicity I recommend that you write all of the button statuses at the same time, and write them directly as a boolean value:
//Write the state of all the buttons in a single line:
writer.write (
x1.isSelected() + "," +
x2.isSelected() + "," +
x3.isSelected() + "," +
x4.isSelected() + "," +
x5.isSelected() + "," +
x6.isSelected() + "," +
x7.isSelected() + "," +
x8.isSelected());
Then reading it back as a single line and just compare each of the 8 items split by the ",":
String[] condition = line.split(csvFilesplitby);
if (condition[0].equalsIgnoreCase("true")){
x1.setSelected(true);
}else if (condition[1].equalsIgnoreCase("true")){
x2.setSelected(true);
}else if (condition[2].equalsIgnoreCase("true")){
x3.setSelected(true);
}else if (condition[3].equalsIgnoreCase("true")){
x4.setSelected(true);
}else if (condition[4].equalsIgnoreCase("true")){
x5.setSelected(true);
}else if (condition[5].equalsIgnoreCase("true")){
x6.setSelected(true);
}else if (condition[6].equalsIgnoreCase("true")){
x7.setSelected(true);
}else if (condition[7].equalsIgnoreCase("true")){
x8.setSelected(true);
}
Obviously you should add some error checking and make sure all buttons are deselected before you set if they are selected or not. But I am sure you can work that part out.
Alternatively you can try something like below :
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.*;
public class Ques1 extends JFrame implements ActionListener {
private JPanel panel;
private JToggleButton[] buttons;
public Ques1() {
initComponents();
buttonswork();
}
private void initComponents() {
buttons = new JToggleButton[6];
panel = new JPanel();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.LINE_AXIS));
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
for (int i = 0; i < buttons.length; i++) {
JToggleButton tb = buttons[i];
tb = new JToggleButton("tb" + (i + 1));
tb.addActionListener(this);
panel.add(tb);
}
getContentPane().add(panel);
pack();
}
private void buttonswork() {
try {
String line = "";
String buttonString = "tb1-0\n"
+ "tb2-0\n"
+ "tb3-0\n"
+ "tb4-1\n"
+ "tb5-1\n"
+ "tb6-0\n";
BufferedReader br = new BufferedReader(new StringReader(buttonString));
while ((line = br.readLine()) != null) {
Component[] components = panel.getComponents();
for (Component c : components) {
if (c instanceof JToggleButton) {
String ac = ((JToggleButton) c).getActionCommand();
((JToggleButton) c).addActionListener(this);
if (ac.equalsIgnoreCase(line.split("-")[0])) {
((JToggleButton) c).setSelected(Integer.parseInt(line.split("-")[1]) == 1);
}
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Ques1().setVisible(true);
});
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "tb1":
//do your work here ...
break;
case "tb2":
//do your work here ...
break;
}
}
}
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.
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);
The below code is used to create a line graph. I am able to display the integers in the TextArea but i am not able to display the sentences above the integers in the text file. How do i rectify this program?
The screenshot of the text file is given below.
I want the first three lines of the text file also to be printed in the TextArea.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.data.xy.*;
public class Pio {
static JFrame frame1 = new JFrame("Graph");
static String URL = null;
static JTextArea txt = new JTextArea();
static JPanel panel = new JPanel();
public static void main(String[] args) throws IOException {
JButton but = new JButton("Open file");
![enter image description here][2]
panel.add(but);
frame1.add(panel, BorderLayout.WEST);
frame1.setVisible(true);
frame1.setSize(1000,400);
but.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFileChooser chooser = new JFileChooser();
int ret = chooser.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
URL = file.getAbsolutePath();
}
File f = new File(URL);
FileReader inputF = null;
try {
inputF = new FileReader(f);
}
catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BufferedReader in = new BufferedReader(inputF);
int[] a = new int[100];
int[] b = new int[100];
String s=null;
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
int i = 0;
while (s != null && i < 100)
{ // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
i++; // don't forget to increment
try {
s = in.readLine();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
try {
in.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("the output of the file is " + f);
XYSeries data = new XYSeries("Line Graph");
int n = a.length;
for (int j = 0; j < n; j++) {
data.add(a[j], b[j]);
}
XYDataset xY = new XYSeriesCollection(data);
JFreeChart chart=ChartFactory.createXYLineChart(
"line graph",
"Cycles",
"Temperature",
xY,
PlotOrientation.VERTICAL,
true,
true,
true);
ChartPanel p=new ChartPanel(chart);
p.setVisible(true);
p.setLocation(100,100);
p.setSize(500,500);
frame1.add(p,BorderLayout.EAST);
}
});
}
}
there nothing about JTextArea, use constructor JTextArea(int rows, int columns)
put JTextArea to the JScrollPane, this JScrollPane put or the EAST or WEST area
put JPanel with JButton to the SOUTH or NORTH area
if ChartPanel doesn't returns any PrefferedSize (I doubt that), or this value isn't correct, then set for own PrefferedSize, put ChartPanel to the CENTER area
as you saw there any code line about setSize, JFrame has implemented BorderLayout in the API
use pack() instead of setSize()
setLocation() if required
last code lines in the ActionListener (your code logics) must be
frame.validate();
frame.repaint();
frame.pack();
in this form (your code logics) is Swing GUI during FileIO unresponsible for Mouse and Key Events, wrap FileIO to the Runnable#Tread or use SwingWorker for redirecting this long and hard task to the background task
create ChartPanel as local variable (as JFrame) and first code line in the ActionListener must be
.
frame.remove(ChartPanel);
Two display two componenets you can use a JSplitPane.
While loading data into your array append it to a JTextArea (area1 in the sample code)
final JTextArea area1 = new JTextArea();
...
area1.append("X=" + a[i] + " Y=" + b[i] + "\n");
Then rather than adding the chart to the frame add both the Chart and the TextArea to the JSplitPane
ChartPanel p = new ChartPanel(chart);
JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
frame1.add( splitpane , BorderLayout.CENTER );
splitpane.add(p);
splitpane.add(area1);
pane.validate();
frame1.validate();
frame1.repaint();
To append data the the JTextArea use
area1.append("Creating a line graph\n");
area1.append("Selected file " + f + "\n");
while (s != null && i < 100) { // your arrays can only hold 1000 ints
String pair[] = s.split(" ");
try{
a[i] = Integer.parseInt(pair[0]);
b[i] = Integer.parseInt(pair[1]);
area1.append("X=" + a[i] + " Y=" + b[i] + "\n");
} catch (NumberFormatException e) {
area1.append(s + "\n");
}
try {
s = in.readLine();
i++; // don't forget to increment
} catch (IOException e1) {
e1.printStackTrace();
}
}
area1.append("Finished reading data\n");
...
In this example I'm assuming that the headder will fail parseInt and (if is does) appending the String s.
I have a csv file of all the stock quotes on in the nyse. first column is symbol second column is the name of the company.
I have a search box and table made in netbeans using the java swing library.
Right now when I enter the name in the box it is returning the correct amount of rows. So for instance if I search GOOG it will only return 2 rows (1 row for the GOOG symbol and one row for the name in the full company name). However the data within the rows is not the correct ones it is just printing the first row of the csv file over and over. here is the code that gets executed when clicking the search button:
package my.Stock;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.*;
public class searchy {
public static void doSearch(String s){
javax.swing.JTable resTable = StockUI.stockUI.getResultTable();
javax.swing.table.DefaultTableModel dtm =
(javax.swing.table.DefaultTableModel) resTable.getModel();
while (dtm.getRowCount()> 0 ) dtm.removeRow(0);
String sym = s.trim().toUpperCase();
try {
//csv file containing data
String strFile = "companylist.csv";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader(strFile));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//create arraylist
ArrayList<String> arrayList = new ArrayList<String>();
//read comma separated file line by line
while( (strLine = br.readLine()) != null){
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
//display csv values
tokenNumber++;
arrayList.add(st.nextToken());
//System.out.println("Line # " + lineNumber + ": "+ st.nextToken() + " " + st.nextToken());
} //end small while
//reset token number
tokenNumber = 0;
} //end big while loop
//send csv to an array
Object[] elements = arrayList.toArray();
/*
for(int i=0; i < elements.length ; i++) {
System.out.println(elements[i]);
} */
Scanner input = new Scanner(System.in);
System.out.print("Enter Ticker symbol");
//String sym = input.next().toUpperCase(); //convert to uppercase to match csv
int j=0;
for(int i=0; i < elements.length ; i++) {
if (((String) elements[i]).contains(sym)){
//System.out.println(elements[i]);
dtm.addRow(elements);
j++;
if (j==25) break; //only show this many results
}
}
}
catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}
I understand why this is happening but I am not sure how to tell it to print the correct lines since I can't use dtm.addRow(elements[i]);
Any help is greatly appreciated.
Try CSVManager.
I collect csv data for stocks from Yahoo, and, oddly enough, every now and then they mess it up by using a company name with a comma in it, e.g., "Dolby, Inc.". Of course, that throws off the parsing of the CSV file. I don't know if this might be your problem.
John Doner
package recommendation.event.test;
import java.io.FileReader;
import com.csvreader.CsvReader;
public class ReadCSV {
public static void main (String [] args){
try {
CsvReader products = new CsvReader("resources/Event Recommendation Engine Challenge/data/test.csv");
products.readHeaders();
while (products.readRecord())
{
String user = products.get("user");
String event = products.get("event");
String invited = products.get("invited");
String timestamp = products.get("timestamp");
System.out.println(user + " : " + event+" : "+invited+" : "+timestamp);
}
products.close();
}catch (Exception e) {
// TODO: handle exception
}
}
}