I'm trying to take data from a CSV file, parse it to a two dimensional array and then return that to a GUI that displays it in a JTable. Doesn't seem to be going too well!
METHOD TO GET FROM CSV
static String[][] readGUIFromPropertyFile(String sFileName, String userName) throws FileNotFoundException
{
String thisLine;
String tempArray[][] = new String[20][4];
int i = 0;
BufferedReader reader = new BufferedReader(new FileReader(sFileName));
try
{
while((thisLine = reader.readLine()) != null)
{
String propertyDetails[] = thisLine.split(",");
if (propertyDetails[0].equals(userName))
{
tempArray[i][0] = propertyDetails[1];
tempArray[i][1] = propertyDetails[2];
tempArray[i][2] = propertyDetails[3];
tempArray[i][3] = propertyDetails[4];
tempArray[i][4] = propertyDetails[5];
i++;
}
}
return tempArray;
}
catch(IOException e)
{
System.out.print("\nProperties do not exist\n");
e.printStackTrace();
}
finally{
try
{ reader.close();
}catch (IOException e){}}
return tempArray;
}
}
CODE FOR GUI
else if (event.getSource() == reload)
{
try {
data = CSVWrite.readGUIFromPropertyFile(propertyFile, userName);
JOptionPane.showMessageDialog(frame, "Properties Loaded");
userPropertyView.add(displayProperties);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(frame, "Properties Not Loaded");
e.printStackTrace();
}
}
I have it working with a command interface so I know the code is working, but I have to implement both a GUI and a command line. I can write from GUI to CSV, no issue, but having trouble displaying it. I've looked into ArrayLists and I actually have a lecture on them tomorrow so that's also a possibility.
I can't use OpenCSV as I have to use default libraries for this.
put String tempArray[][] as JTables constructor JTable(Object[][] rowData, Object[] columnNames) directly
better way should be to add a new row to the TableModel, not replace the JTable on runtime, more in tutorial Creating a Table Model
Related
I have a problem to store data in this hashmap, I'm programming in Java.
My system consists of some chats, in the hash map I have to insert chats as indexes and the list of users who are connected to a specific chat, my problem is the initialization of the hashmap, as I only have to enter the chats but the arraylists are empty because there is no user connected, only I cannot understand how to do this correctly.
This is a little sample of my code:
public class Master {
private HashMap<String, ArrayList<String>> chatBox;
public Master() {
chatBox = new HashMap<String, ArrayList<String>>();
}
public insert() {
FileReader fr;
BufferedReader br;
try {
fr = new FileReader("listChat.txt");
br = new BufferedReader(fr);
while(true) {
String topic = br.readLine();
if(topic == null)
break;
chatBox.put(topic, null);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I will suggest you to change the code that way by creating an empty ArrayList when you add a new element in the hashmap:
while(true) {
String topic = br.readLine();
if(topic == null)
break;
chatBox.put(topic, new ArrayList<String>());
}
When you will have to update this topic with messages, you get the value for the key "topic" and add new elements in the ArrayList
I have to parse csv file .
number of columns would be variable.
I have written following code for fixed columns.
I have used csvtobean and MappingStrategy apis for parsing.
Please help me how can I create mappings dynamically.
public class OpencsvExecutor2 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
CsvToBean csv = new CsvToBean();
String csvFilename="C:\\Users\\ersvvwa\\Desktop\\taks\\supercsv\\20160511-0750--MaS_GsmrRel\\20160511-0750--MaS_GsmrRel.txt";
CSVReader csvReader = null;
List objList=new ArrayList<DataBean>();
try {
FileInputStream fis = new FileInputStream(csvFilename);
BufferedReader myInput = new BufferedReader(new InputStreamReader(fis));
csvReader = new CSVReader(new InputStreamReader(new FileInputStream(csvFilename), "UTF-8"), ' ', '\'', 1);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
csvReader.getRecordsRead();
//Set column mapping strategy
List<DataBean> list = csv.parse(setColumMapping(csvReader), csvReader);
for (Object object : list) {
DataBean obj = (DataBean) object;
// System.out.println(obj.Col1);
objList.add(obj);
}
csvReader.close();
System.out.println("list size "+list.size());
System.out.println("objList size "+objList.size());
String outFile="C:\\Users\\ersvvwa\\Desktop\\taks\\supercsv\\20160511-0750--MaS_GsmrRel\\20160511-0750--MaS_GsmrRel.csv";
try {
CSVWriter csvWriter = null;
csvWriter = new CSVWriter(new FileWriter(outFile),CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER);
//csvWriter = new CSVWriter(out,CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER);
String[] columns = new String[] {"col1","col2","col3","col4"};
// Writer w= new FileWriter(out);
BeanToCsv bc = new BeanToCsv();
List ls;
csvWriter.writeNext(columns);
//bc.write(setColumMapping(), csvWriter, objList);
System.out.println("complete");
csvWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static MappingStrategy setColumMapping(CSVReader csvReader) throws IOException {
// TODO Auto-generated method stub
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(DataBean2.class);
String[] columns = new String[] {"col1","col2","col3","col4"};
strategy.setColumnMapping(columns);
return strategy;
}
}
If I understood correctly, you can read the file line by line and use split.
Example READ CSV: Example extracted from mkyong
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadCVS {
public static void main(String[] args) {
ReadCVS obj = new ReadCVS();
obj.run();
}
public void run() {
String csvFile = "/Users/mkyong/Downloads/GeoIPCountryWhois.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("Country [code= " + country[4]
+ " , name=" + country[5] + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
Example for WRITE a CSV file: Example extracted from mkyong
import java.io.FileWriter;
import java.io.IOException;
public class GenerateCsv
{
public static void main(String [] args)
{
generateCsvFile("c:\\test.csv");
}
private static void generateCsvFile(String sFileName)
{
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append("DisplayName");
writer.append(',');
writer.append("Age");
writer.append('\n');
writer.append("MKYONG");
writer.append(',');
writer.append("26");
writer.append('\n');
writer.append("YOUR NAME");
writer.append(',');
writer.append("29");
writer.append('\n');
//generate whatever data you want
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
However, I would recommend to use a library. There are many (e.g., opencsv, Apache Commons CSV, Jackson Dataformat CSV, etc). You don't have to re-invent the wheel.
OPENCSV website has a lot of example that you can use.
If you Google "opencsv read example" you will get a lot of examples using the OPENCSV library (e.g., "Parse / Read / write CSV files : OpenCSV tutorial")
Hopefully this would help you!.
Assuming that your code works, I would try to use Generics for the setColumnMapping method.
The method setType gets a parameter "Class type". Use this as a parameter for your own method setColumnMapping e.g., (CSVReader csvReader, Class type). This way you can pass the DataBean2.class to the method, or any other class. Furthermore you need a variable column to bean mapping, because {"col1","col2","col3","col4"} is not sufficient for every bean, as you know. Think about how you can make this dynamic (you can pass a String[] to the setColumnMethod for example).
You also need to adjust List usage inside your main apparently.
I suggest looking for a brief tutorial on java generics before you start programming.
Finally i was able to parse csv and write it in desired format like
csvWriter = new CSVWriter(new FileWriter(outFile),CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER);
csvReader = new CSVReader(new InputStreamReader(new FileInputStream(csvFilename), "UTF-8"), ' ');
String header = "NW,MSC,BSC,CELL,CELL_0";
List<String> headerList = new ArrayList<String>();
headerList.add(header);
csvWriter.writeNext(headerList.toArray(new String[headerList.size()]));
while ((nextLine = csvReader.readNext()) != null) {
// nextLine[] is an array of values from the line
for(int j=0;j< nextLine.length;j++){
// System.out.println("next " +nextLine[1]+" "+nextLine [2]+ " "+nextLine [2]);
if(nextLine[j].contains("cell")||
nextLine[j].equalsIgnoreCase("NW") ||
nextLine[j].equalsIgnoreCase("MSC") ||
nextLine[j].equalsIgnoreCase("BSC") ||
nextLine[j].equalsIgnoreCase("CELL")){
hm.put(nextLine[j], j);
}
}
break;
}
String[] out=null;
while ((row = csvReader.readNext()) != null) {
String [] arr=new String[4];
outList = new ArrayList<>();
innerList = new ArrayList<>();
finalList=new ArrayList<String[]>();
String[] str=null;
int x=4;
for(int y=0; y<hm.size()-10;y++){
if(!row[x].equalsIgnoreCase("NULL")|| !row[x].equals(" ")){
System.out.println("x "+x);
str=new String[]{row[0],row[1],row[2],row[3],row[x]};
}
finalList.add(str);;
x=x+3;
}
csvWriter.writeAll(finalList);
break;
}
csvReader.close();
csvWriter.close();
}
I'm working on rewriting my simple Contacts app from normal JAVA FX to FXML.THe problem is in Lambda expressions. I have interface like:
interface ObjectCreator {
void create(String[] array);
}
And the problem is when i use this CSVFileReader:
public static class CSVFileReader {
String fileName;
CSVFileReader(String fileName) {
this.fileName = fileName;
}
void read(ObjectCreator creator) {
try {
BufferedReader csv = new BufferedReader(new FileReader(fileName));
String row = csv.readLine();
while (row != null) {
creator.create(row.split(","));
row = csv.readLine();
}
csv.close();
} catch (IOException e) {
}
}
}
In this code i use lambda expression to read Contacts from file:
#FXML
public void openFile() {
FileChooser fileChooser = new FileChooser();
File fileE = fileChooser.showOpenDialog(scene.getWindow());
if (fileE != null) {
CSVFileReader reader = new CSVFileReader(fileE.getName());
data.clear();
reader.read(v ->
data.add(new Contact(v[0], v[1], v[2], v[3])));
}
System.out.println("open list");
}
I use JDK 1.8.65 so preeety new one. Problem is that there is no error or exception just looks like code "v->data.add(new Contact(v[0], v[1], v[2], v[3]))" would not be invoked.
Question is am I doing something wrong or it just wont be working??
Ok no question, after futher studying my app i discovered i was taking
fileE.getName();
and i should take
fileE.getAbsolutePath();
So the app would look in proper location for a file.
I've been googling all over the place for information on how to display content from a .txt file onto a web page using JSF with no success.
From what I think/guess, the basic jsf form would be something like
<h:outputText value="#{beanName.printTextFileMethod}"/>
or something.
Help on how to set up bean appreciated. I tried playing with InputStream/BufferedStream, having a lot of problem just trying to get rid of the red lines in codes. Also I'm absolutely horrid at defining relative path. And absolute path doesn't seem to work with inputstream?
Thank you for your time.
public class TextFileBean{
String completeMessage = null;
public TextFileBean(){
try{
//read data from the text file
java.io.BufferedReader in=
new java.io.BufferedReader(
new java.io.InputStreamReader(
TextFileBean.this.getClass().
getResourceAsStream("txtFile.txt"
)));
System.out.println("in :" +in);
readData(in);
in.close();
} catch (java.io.IOException IOex) {
System.out.println("IO Error :" +IOex);
}
}
private void readData(BufferedReader br) {
// dosomethig
String line = null;
StringBuffer appendMessage = null;
try {
appendMessage = new StringBuffer(16384);
while ((line = br.readLine()) != null) {
appendMessage.append(line);
appendMessage.append('\n');
}
if (appendMessage != null) {
completeMessage = appendMessage.toString();
}
} catch (Exception e) {
}
}
public String printTextFileMethod()
{
System.out.println("completeMessage:: "+ completeMessage);
return completeMessage;
}
}
I have a problem when storing data (written to a GUI) in a JTable I have already created. The problem is, when I click the add button in the GUI, instead of displaying it in the JTable, it opens another window and displays it there. So it adds, but it doesnt display it to the table. Heres the part of the code that display the info in another window:
import java.lang.Object;
import java.io.*;
import java.util.*;
public class MemberManager {
File custFile;
private Member m1 =
new Member("M0001", "Mark", "Abela", "13/05/90", "121 Kent Street", "21469432", "99456209");
private Member m2 =
new Member("M0002", "John", "Sant", "25/11/84", "55 Golden Road", "21226932", "79513625");
private ArrayList<Member> memMemb = new ArrayList<Member>();
public MemberManager(){
memMemb.add(m1);
memMemb.add(m2);
}
public String[][] getMembers(){
int pos = 0;
//Creating the table with the players data
String data [][] = new String[memMemb.size()][8];
for (Object obj : memMemb){
Member mem = (Member)(obj);
data[pos][0] = mem.getID();
data[pos][1] = mem.getName();
data[pos][2] = mem.getSurname();
data[pos][3] = mem.getDob();
data[pos][4] = mem.getAddress();
data[pos][5] = mem.getTel();
data[pos][6] = mem.getMob();
}
return data;
}
public void addMember(String id, String name, String surname, String dob, String address, String tel, String mob){
Member tempMem = new Member();
tempMem.setID(id);
tempMem.setName(name);
tempMem.setSurname(surname);
tempMem.setDob(dob);
tempMem.setAddress(address);
tempMem.setTel(tel);
tempMem.setMob(mob);
memMemb.add(tempMem);
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("Member Data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(memMemb);
oos.flush();
}
catch(IOException e) {
e.printStackTrace();
}
finally {
try {
fos.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
try {
// read back
fis = new FileInputStream("Member Data");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
memMemb = (ArrayList<Member>) obj;
ArrayList<Member> listFromFile = (ArrayList) obj;
for (Member member: listFromFile) {
System.out.println(member.toString());
}
}catch (IOException io){
System.err.println("Cannot access or write to file");
}catch (Exception e){
e.printStackTrace();
}
finally {
try {
fis.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
The JTable im using is the default table model thats in a different package. I used mouseListener on the button to add the data... here's part of the code...:-
memAddOk.addMouseListener(this);
memAddExit.addMouseListener(this);
}
public void mouseClicked(MouseEvent e){
if (e.getSource().equals(memAddOk)){
id = textBox[0].getText();
name = textBox[1].getText();
surname = textBox[2].getText();
dob = textBox[3].getText();
address = textBox[4].getText();
tel = textBox[5].getText();
mob = textBox[6].getText();
MemberManager tempData = new MemberManager();
tempData.addMember(id, name, surname, dob, address, tel, mob);
} else
if (e.getSource().equals(memAddExit)) {
this.dispose();
}
}
How do I get this code to store in the JTable?
The problem is, when I click the add button in the GUI, instead of displaying it in the JTable, it opens another window and displays it there.
It's just doing what you tell it to do:
public void mouseClicked(MouseEvent e){
if (e.getSource().equals(memAddOk)){
id = textBox[0].getText();
// .... etc..
// !!!! *** Here you create a new MemberManager object *** !!!!
MemberManager tempData = new MemberManager();
tempData.addMember(id, name, surname, dob, address, tel, mob);
} else
//... etc..
Solution:
Don't create a new MemberManager object in your listener.
Instead make sure that your listener class has a reference to the currently displayed MemberManager object so you can add a Patient to it.
You often get this reference by passing a MemberManager into the listener's constructor or via a setter method parameter.
Again, don't use MouseListeners on JButtons but instead use ActionListeners as that's what they're specifically built for. MouseListeners can cause strange behaviors including but not limited to a button that still works despite being disabled.
1) use SwingWorker or Runnable#Thread for loading value on the background from File IO or Database
2) define JTable and DefaultTableModel once time, start background task for loading data from File or Database, simple example