How to load text data into a table using Java - 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));.

Related

How to remove a row from a csv file if that row contains a certain data in java

I have a csv file that basically mimics a database and my goal is to remove a row from that csv if the csv file contains that username input I provide
the current csv file is:
Jack chan,customer,jack#yorku.ca,jack12,3144134414,13 Arboretum,user2
Donald tusk,customer,donald#yorku.ca,donald1,1213141114,14 Arboretum,user3
tom jack,customer,tom11#yahoo.com,tom44,131344122,14 wells st,user34
jack,parking officer,12rfw#hmail.com,jack,12131131134,12ddcscs,peo1
jewel khan,parking officer,jkhan#hotmail.com,jwel12,2131412141,12 wliis str,peo2
shane li,parking officer,shane#gmail.com,shaneli,1343513414,13 mac st,peo33
james chang,parking officer,james15#gmail.com,james12,31452434114,13 chang st,peo77
my objective is to remove the row of say Shane li using his username "shaneli" and not causing any change to other data. but the current code I have is not causing the file's other data to change
the expected output csv file is row with shaneli gets deleted with other rows remaining intact:
Jack chan,customer,jack#yorku.ca,jack12,3144134414,13 Arboretum,user2
Donald tusk,customer,donald#yorku.ca,donald1,1213141114,14 Arboretum,user3
tom jack,customer,tom11#yahoo.com,tom44,131344122,14 wells st,user34
jack,parking officer,12rfw#hmail.com,jack,12131131134,12ddcscs,peo1
jewel khan,parking officer,jkhan#hotmail.com,jwel12,2131412141,12 wliis str,peo2
james chang,parking officer,james15#gmail.com,james12,31452434114,13 chang st,peo77
this is the code java code I have and I need a java solution:
private static String userPath = "/CSVs/database.csv";
public void removeUser(String name,String userType,String email,String userName,String phoneNumber,String address,String password) {
// FIX THIS
String tmpFile = "tmp.csv";
// String target1 = ""; String target2 = ""; String target3 = ""; String target4 = ""; String target5 = "";String target6 = "";String target7 = "";
String target = "";
File oldFile = new File(userPath);
File newFile = new File(tmpFile);
System.out.println(userName);
try {
FileWriter fw = new FileWriter(tmpFile, true);
BufferedWriter bfw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bfw);
x = new Scanner(new File(userPath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
target = x.next();
if (!target.equals(userName)) {
pw.printf("%s,%s,%s,%s,%s,%s,%s\n", name, userType,email,userName,phoneNumber,address,password);
// pw.println(target + "," + target + "," + target + "," + target + "," + target + "," + target + "," + target);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dmp = new File(userPath);
newFile.renameTo(dmp);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Please advice
Thanks in advance !!
Solution
The way I've come up with is to do the following:
Create a new file
If the username is not equal, add line, otherwise skip it
Just as we've listed out our steps, we can create a function to do each one.
Code
1) Creating a new file
private void createFile(){
try {
File myObj = new File("CSVs/tmpFile.csv");
} catch (IOException e) {
e.printStackTrace();
}
}
We can then create the file which will be stored at the desired file path and stored as tmpFile.csv.
2) If the username are not equal, add line
private void addDataContents(String userNameToDelete){
try{
String userPath = "CSVs/database.csv";
BufferedReader csvReader = new BufferedReader(new FileReader("CSVs/database.csv"));
String row;
FileWriter myWriter = new FileWriter("CSVs/tmpFile.csv");
while (((row = csvReader.readLine()) != null)){
String[] line = row.split(",");
if (!line[3].equals(userNameToDelete)){
myWriter.write(row + "\n");
}
}
myWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
We then read through the contents of database.csv. We read every line one by one and split the line up by commas as it is a CSV file ( Comma Separated Values ). As the username will always be stored in the 3rd index, we can compare the username we wish to delete with the value stored at the index. If they are not the same, we can go ahead and write the line to our new file. If they are the same, our loop will just continue onto the next line.
Final Notes
I hope everything is easy to read and understandable.
You need to delete the whole row containing specific data from a CSV file. The Java code will be rather long if you try to use the high-level language to do this. It is very simple to accomplish the task in SPL, an open-source Java package. You just need one line of code, as shown below:
A
1
>file("tmp.csv").export#c(file("database.csv").import#wc().select(~(4)!=userNameToDelete))
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as removeUser.splx and invoke it in Java in the same way you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call removeUser(?)");
st.setObject(1,"shaneli");
st.execute();
…

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.

Show objects in string array side by side in a text Area using java

I wanted to read specific columns written in my text file and show this specific columns onto my text Area side by side. I manage to read the desired columns and show them to my text area using the codes below:
try
{
ArrayList<String> totalResult1 = new ArrayList<String>();
ArrayList<String> totalResult2 = new ArrayList<String>();
[enter image description here][1]ArrayList<String> totalResult3 = new ArrayList<String>();
try
{
FileInputStream fStream = new FileInputStream("hubo\\" + "table" + ".txt");
DataInputStream in = new DataInputStream(fStream);
BufferedReader br = new BufferedReader (new InputStreamReader(in));
String strLine;
while((strLine = br.readLine()) != null)
{
strLine = strLine.trim();
if((strLine.length()!=0) && (strLine.charAt(0) !='#'))
{
String[] employee = strLine.split("\\s+");
totalResult1.add(employee[0]);
totalResult2.add(employee[1]);
totalResult3.add(employee[2]);
}
}
for(String s1 : totalResult1)
{
showArea.append(s1.toString() + "\n");
}
for(String s2 : totalResult2)
{
showArea.append("\t" + "\t" + s2.toString() + "\n");
}
in.close();
}
catch (Exception e1)
{
}
}
catch(Exception e1)
{
}
This is my result
Alex Santos
Troy Smith
John Love
Married
Single
Married
My desired results are this:
Alex Santos Married
Troy Smith Single
John Love Married
I want to show to my text Area both of my columns side by side, can anyone point me to the right direction.
Your solution is close, but not quite. When you append the employe names from totalResult1 you go to a new line each time. So when you add values from the second list, you are already bellow the names. To create a table like display, you would need to add values from each list at the same time:
for(int i = 0; i < totalResult1.size(); i++){
showArea.append(totalResult1.get(i) + "\t\t");
showArea.append(totalResult2.get(i) + "\n");
}
The should do the trick. But in general, when you want a table you shouldn't use a text area, you can use a table control instead.

Java formatting string of doubles to output file

My code uses BufferedReader to read columns of data in a text file. The text file looks like:
Year.....H2OIN....CO2IN
0.000......0.0..........0.0
1.000......2.0..........6.0
2.000......3.0..........7.0
3.000......4.0..........8.0
My formatting code looks like:
try {
FileInputStream file = new FileInputStream(inputFile);
BufferedReader in = new BufferedReader(new InputStreamReader(file));
f = new Formatter("M:\\TESTPACK\\AL6000803OUT.TXT");
while((line = in.readLine()) != null) {
if (line.startsWith(" 0.000"))
break;
}
while((line = in.readLine()) != null) {
stream = line.split(parse);
start = line.substring(6,9);
if (start.equals("000")) {
H2OIN = Double.parseDouble(stream[1]);
CO2IN = Double.parseDouble(stream[2]);
f.format("%s ", H2OIN);
f.format("%s ", CO2IN);
}
}
}catch (FileNotFoundException e) {
}catch (IOException e) {
}
f.close();
However, my output file looks like:
2.0 6.0 3.0 7.0 4.0 8.0
While I want it to look like:
2.0 3.0 4.0
6.0 7.0 8.0
I need a suggestion for how to apply formatting to the data strings, not the data itself. Essentially I need to transpose columns of data to rows of data. The duplicate post suggested was not the problem I'm trying to solve.
You'll need to include two StringBuffers. One for your H2OIN row and another for your CO2IN row.
Like so:
With your other declarations...
StringBuffer H2OINRow = new StringBuffer();
StringBuffer CO2INRow = new StringBuffer();
In your if (start.equals("000")) block...
// in place of the f.format calls
H2OINRow.Append(H2OIN + " ");
CO2INRow.Append(CO2IN + " ");
After your while loops...
f.format("%s\n", H2OINRow);
f.format("%s\n", CO2INRow);
I suggest you gather all the values you want on each line in a different List.
So instead, your while loop would look like :
List<String> h2oValues = new ArrayList<String>();
List<String> c02Values = new ArrayList<String>();
while((line = in.readLine()) != null) {
stream = line.split(parse);
start = line.substring(6,9);
if (start.equals("000")) {
H2OIN = Double.parseDouble(stream[1]);
CO2IN = Double.parseDouble(stream[2]);
h2oValues.add(H2OIN);
c02Values.add(CO2IN);
}
}
After that, loop the values of h2oValues to write them in a line and do the same for c02Values
for (String value : h2oValues) {
f.format("%s ", value);
}
// Add a end of line character... using the system one, you might want to change that
f.format(%n);
for (String value : h2oValues) {
f.format("%s ", c02Values);
}
For the end line, see this question if you want to change it.

Using a loop I want to find the value of a column from my CSV file java

Forgive me if this is a basic (or not very well explained) question, I am fairly new to Java and have been reading extensive material as well as trying to understand the relevant Javadoc but to no avail.
To give a brief background as to what I am trying to create, I have created a reader class which reads data in from a csv file (4 lines long) including fields such as Item ID, price, description etc. I have created a separate demo class that displays the details of this csv file (through creating an instance of my reader class) and am now trying to create a method that asks the user to input an Item ID that then displays the corresponding Item, based on the ID input by the user. The part I am stuck on is accessing specific rows/columns in a csv file and then comparing these with a given string (entered by the user which corresponds to a specific field in the csv file)
This is what I have come up with thus far:
input = new Scanner(System.in);
System.out.println("Enter a product code");
String prodC = input.next();
//Here I want to know if there is a way of accessing a field in a csv file
Any ideas would be greatly appreciated.
UPDATE
Thank you for quick responses, am currently reading through and seeing how I can try to implement the various techniques. In response to the comment asking about the file reader, this is how I have set that out:
public CatalogueReader(String filename) throws FileNotFoundException {
this.filename = filename;
this.catalogue = new Catalogue();
Scanner csvFile;
try {
csvFile = new Scanner(new File(filename));
} catch (FileNotFoundException fnf) {
throw new FileNotFoundException("File has not been found!");
}
csvFile.useDelimiter("\n");
boolean first = true;
String productCode;
double price;
String description;
double weight;
int rating;
String category;
boolean ageRestriction;
String csvRows;
while (csvFile.hasNextLine()) {
csvRows = csvFile.nextLine();
if (first) {
first = false;
continue;
}
System.out.println(csvRows);
String[] fields = csvRows.split(",");
productCode = (fields[0].trim());
price = Double.parseDouble(fields[1].trim());
description = fields[2].trim();
weight = Double.parseDouble(fields[3].trim());
rating = Integer.parseInt(fields[4].trim());
category = fields[5].trim();
ageRestriction = Boolean.parseBoolean(fields[6].trim());
catalogue.addAProduct(new Item(productCode, price, description, weight, rating, category, ageRestriction));
}
csvFile.close();
}
}
ok so for a CSV file like this:
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
here is a sample of how to read using Java Native Libraries
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVReader {
public static void main(String[] args) {
CSVReader obj = new CSVReader();
obj.run();
}
public void run() {
String csvFile = YOURFILEPATHHERE ;
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");
}
}
does this help?
If you are just doing a single look-up and then exiting then just remember the String you are looking for. As you parse the lines compare to see if you have a match and if you do then return that line.
For repeated searches that would be very inefficient though. Assuming your data set is not too large for memory you would be better off parsing the file and putting it into a Map:
Map<String, Data> dataMap = new HashMap<>();
Parse the file, putting all the lines into the map
Then the lookup just becomes:
Data d = dataMap.get(lineKey);
If d is null then there is no matching line. If it not null then you have found your line.
You can create an array list of object. An object for each line in the CSV. Then search the array object with your search criteria.
User CSVReader framework to read the csv file. Sample code (not exactly what you want)
FileInputStream fis = new FileInputStream(file);
CSVReader reader = new CSVReader(new BufferedReader( new InputStreamReader(fis, "UTF-8" )));
ArrayList<String> row = new ArrayList<String>();
ArrayList<Entry> entries = new ArrayList<Entry>();
// a line = ID, Name, Price, Description
while (!reader.isEOF()) {
reader.readFields(row);
if( row.size() >= 4)
entries.add(new Entry(row.get(0), row.get(1), row.get(2), row.get(3)));
}
System.out.println("Size : "+entries);

Categories

Resources