Reading Files to Store their Data in an Array - java

The program that I am writing is in Java.
I am attempting to make my program read the file "name.txt" and store the values of the text file in an array.
So far I am using a text file that will be read in my main program, a service class called People.java which will be used as a template for my program, and my main program called Names.java which will read the text file and store its values into an array.
name.txt:
John!Doe
Jane!Doe
Mike!Smith
John!Smith
George!Smith
People.java:
public class People
{
String firstname = " ";
String lastname = " ";
public People()
{
firstname = "First Name";
lastname = "Last Name";
}
public People(String firnam, String lasnam)
{
firstname = firnam;
lastname = lasnam;
}
}
Names.java:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Names
{
public static void main(String[]args)
{
String a = " ";
String b = "empty";
String c = "empty";
int counter = 0;
People[]peoplearray=new People[5];
try
{
File names = new File("name.txt");
Scanner read = new Scanner(names);
while(read.hasNext())
{
a = read.next();
StringTokenizer token = new StringTokenizer("!", a);
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
}
People p = new People(b,c);
peoplearray[counter]=p;
++counter;
}
}
catch(IOException ioe1)
{
System.out.println("There was a problem reading the file.");
}
System.out.println(peoplearray[0]);
}
}
As I show in my program, I tried to print the value of peoplearray[0], but when I do this, my output reads: "empty empty" which are the values I gave String b and String c when I instantiated them.
If the program were working corrrectly, the value of peoplearray[0] should be, "John Doe" as those are the appropriate values in "names.txt"
What can I do to fix this problem?
Thanks!

StringTokenizer(String str, String delim)
is the constructor of StringTokenizer.
You have written it wrong .
Just change your line
StringTokenizer token = new StringTokenizer("!", a); to
StringTokenizer token = new StringTokenizer(a, "!");

Just change it a little bit
StringTokenizer token = new StringTokenizer(a, "!");
while(token.hasMoreTokens())
{
b = token.nextToken();
c = token.nextToken();
}
//do something with them

Related

Reading from CSV file and create object

I'm a complete beginner to Java and I have been given an exercise where I have to read data from a CSV file and then create an object for each line of the file as the program reads the data from the file.
Here is part of the CSV file:
1,Jay, Walker,91 Boland Drive,BAGOTVILLE,NSW,2477
2,Mel, Lowe,45 Ocean Drive,MILLERS POINT,NSW,2000
3,Hugh, Manatee,32 Edgecliff Road,REDFERN,NSW,2016
4,Elizabeth, Turner,93 Webb Road,MOUNT HUTTON,NSW,2290
and so on ...
Here is my code that reads data from the CSV file:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Client_19918424 {
public static void main(String[] args) throws FileNotFoundException {
File inFile = new File("clients.txt");
Scanner inputFile = new Scanner(inFile);
String str;
String[] tokens;
while (inputFile.hasNext()) {
str = inputFile.nextLine(); // read a line of text from the file
tokens = str.split(","); // split the line using commas as delimiter
System.out.println("Client ID: " + tokens[0]);
System.out.println("Client First Name: " + tokens[1]);
System.out.println("Client Sur Name: " + tokens[2]);
System.out.println("Street Address: " + tokens[3]);
System.out.println("Suburb: " + tokens[4]);
System.out.println("State: " + tokens[5]);
System.out.println("Postcode:" + tokens[6]);
System.out.println( );
} // end while
}
}
this is my Client class (have constructor):
public class Client {
private int clientID;
private String firstName;
private String surName;
private String street;
private String suburb;
private String state;
private int postcode;
// constructor
public Client (int ID, String fName, String sName, String str, String sb, String sta, int pCode) {
clientID = ID;
firstName = fName;
surName = sName;
street = str;
suburb = sb;
state = sta;
postcode = pCode;
}
However I don't know how to create a Client object for each line of text file as the program reads data from file.
like for the first line make something like this:
Client client1 = new Client(1, "Jay", "Walker", "91 Boland Drive", "BAGOTVILLE", "NSW", 2477);
And then add it to array:
Client[0] = client1;
can someone help me to solve this question, im really appreciate.
You are almost there.
All that's left to do is to map each token that is already printed to the corresponding fields in the Client class. Since token[0] doesn't really tell what value it holds you could do it in three ways:
while (inputFile.hasNext()) {
str = inputFile.nextLine();
tokens = str.split(",");
// Because tokens[0] is of type String but clientID is of type int,
// we need to parse it and get the integer representation.
int clientID = Integer.parseInt(tokens[0]);
// Both of type String, no parsing required.
String firstName = tokens[1];
String surName = tokens[2];
String street = tokens[3];
String suburb = tokens[4];
String state = tokens[5];
int postcode = Integer.parseInt(tokens[6]);
// Then all that's left to do is to create a new object of `Client` type
// and pass all the gathered information.
Client client = new Client(clientID, firstName, surName, street, suburb, state, postcode);
System.out.println(client + "\n");
}
At this moment if we try to print the client (last line) we will get something like this: com.example.demo.Client#30a3107a. That's because we didn't tell how we want our object to be displayed. For that toString() method in Client class has to be overriden like so:
#Override
public String toString() {
return "Client ID: " + clientID + "\n" + "Client First Name: " + firstName + "\n"
+ "Client Sur Name: " + surName + "\n" + "Street Address: " + street + "\n"
+ "Suburb: " + suburb + "\n" + "State: " + state + "\n" + "Postcode: " + postcode;
}
It will give the exact output that is in your example.
It is achievable to create the class by passing those tokens directly as well, without the creation of temporary variables:
Client client = new Client(Integer.parseInt(tokens[0]), tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], Integer.parseInt(tokens[6]));
This case brings us to the third solution with setters and getters.
The variables that describe the Client are already defined, it is possible to pass them to assemble the perfect object, but it is not possible to retrieve them. Instead of setting the variables directly in the constructor, we can create a special method that will do the job, for instance:
// Other fields omitted
private int clientID;
// The empty constructor required for later usage,
// since right now, we can't create the object without specifying every property.
public Client() {
}
// This method does exactly the same thing that was done before but
// in the constructor directly
public void setClientID(int clientID) {
this.clientID = clientID;
}
// This method will assist in retrieving the set data from above.
public int getClientID() {
return clientID;
}
And then the while loop would look like this instead:
Client client = new Client();
client.setClientID(Integer.parseInt(tokens[0]));
client.setFirstName(tokens[1]);
client.setSurName(tokens[2]);
client.setStreet(tokens[3]);
client.setSuburb(tokens[4]);
client.setState(tokens[5]);
client.setPostcode(Integer.parseInt(tokens[6]));
And to get those values:
System.out.println("Client ID: " + client.getClientID());
Or you could use the constructor with the fields to create the client, add getters in the class, omit both setters, and the empty constructor if the creation of the client should only be possible with all the fields present.

Java help needed for a code like Autocorrect

I am writing a program which is the opposite of Auto Correct. The logic is that the user enters a sentence, when a button is pressed, the grammatical opposite of the sentence entered by the user should be displayed. I am roughly able to get the code. I used the matcher logic.But i am not able to get the desired output. I am linking the code with this question. Can anyone help me please?
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String input = editText.getText().toString();
String store = input;
String store1 [] = store.split(" ");
String correct[] = {"is","shall","this","can","will"};
String wrong [] = {"was","should","that","could","would"};
String output = "";
for (int i=0;i<store1.length;i++) {
for(int j=0;j<correct.length;j++){
if(store1[i].matches(correct[j])) {
output = input.replace(store1[i], wrong[j]);
//store1[i] = wrong[j];
}
else
{
input.replace(store1[i], store1[i]);
//store1[i] = store1[i];
}
}
mTextView.setText(output);
}
}});
By looking at your code, I've found some redundancy and unused variable. Shown as below.
String store = input;
String store1 [] = store.split(" ");
As shown below, I did some cleanup for you and implement your logic using Map interface. The wrong value must be the Key of the map so that we can easily determine is the word a wrong value using Map.containKeys(word). If key is found then we concatenate the output variable with the correct word.
String input = editText.getText().toString().split(" ");
Map<String, String> pairs = new HashMap<>();
pairs.put("is", "was");
pairs.put("shall", "should");
pairs.put("this", "that");
pairs.put("can", "could");
pairs.put("will", "would");
String output = "";
for (String word : input) {
if (pairs.containsKey(word)) {
output = output + pairs.get(word) + " ";
} else {
output = output + word + " ";
}
}
mTextView.setText(output.trim());

I'm having problems with the .split() method using "," as the delimeter. Java

So for my current school project we have to read input from a file containing info on the periodic table of elements. Essentially I have to seperate bits of each line which has info on an element and put them into seperate string values.
Here the bit of code I'm having problems with.
for(int i=0;inputStream.hasNextLine();i++)
{
String line = inputStream.nextLine();
String[] info = line.split(",");
name=info[0];
atomicNumber=info[1];
symbol=info[2];
boilingPoint=info[3];
meltingPoint=info[4];
density=info[5];
molecularWeight=info[6];
elementInfo[i]= new Element(name,atomicNumber,symbol,boilingPoint,meltingPoint,density,molecularWeight);
It stores everything in the proper place except for the information for the density and the molecular Weight which i get null values for. I couldn't find any info why it isn't working for those last two Strings.
Example output:
Element Name: actinium
Atomic Number: 89
Symbol: Ac
Boiling Point: 3470
Melting Point: 1324
Density: null
Molecular Weight: null
Here's the constructor for the element object:
public Element(String name,String atomicNumber,String symbol, String boilingPoint, String meltingPoint, String density, String molecularWeight)
{
this.name=name;
this.atomicNumber=atomicNumber;
this.symbol=symbol;
this.boilingPoint=boilingPoint;
this.meltingPoint=meltingPoint;
this.density=density;
this.molecularWeight=molecularWeight;
}
You can try this,
// mean into file that info not exist, in that case take its default i.e. empty
info[5] == null ? "empty" : info[5];
info[6] == null ? "empty" : info[6];
Definitely the file you are reading contains 7 elements, else the following code will result in an error
density=info[5]; molecularWeight=info[6];
Example:
public static void main(String args[]) {
String line = "1,2,3,4,5,,";
String[] info = line.split(",");
System.out.println(info.length);
System.out.println(Arrays.deepToString(info));
}
The Output of the above snippet is 5 and [1, 2, 3, 4, 5]
Here we cannot use info[5] or info[6] as it will result in an error.
So your data is correct and you are capturing all the values.
I believe the problem is in printing the output, but you have not mentioned that code in your query to investigate deep.
Hope it helped.
String.split() never ever returns null (see here), which means the problem is not with split() method but, elsewhere. The split() method seem to return at least 7 chunks of data and this is because you are not getting ArrayIndexOutOfBoundException when you do this molecularWeight=info[6].
Then the problem is elsewhere and you can find out by reviewing your code and there must be something you are missing, something really really simple.
Let's assume you have the following input (2 elements):
actinium,89,Da,3470,1926,missing-x,missing-y
actinium,13,Gk,5480,1124,missing-z,missing-w
I used majority of your code, and developed a sample use cases to read the above two elements from file and store them in a list and print them back. I used List<Element> instead of your Element[] solution as well as overrided toString() in Element class to pretty-print the elements with Java 8's stream, see below and compare with your solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFromFileElements {
public static void main(String... args) throws FileNotFoundException {
// You can use list instead of Element[] array
List<Element> elementInfo = new ArrayList<Element>();
//file containing the input
File file = new File("C:\\test_java\\elements.txt");
//open input stream to the file
Scanner input = new Scanner(file);
//as long as there is nextLine() keep looping
while(input.hasNextLine()) {
String line = input.nextLine();
String[] chunk = line.split(",");
Element e = new Element(chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5],
chunk[6]);
//add to the list of Element/s
elementInfo.add(e);
}
//close input stream
input.close();
//java 8 stream iterator through collection
elementInfo.stream().forEach((temp) -> {
//temp.toString() uses the overrided toString() of element class
System.out.println(temp.toString());
});
}
}
class Element {
String name;
String atomicNumber;
String symbol;
String boilingPoint;
String meltingPoint;
String density;
String molecularWeight;
public Element(String name, String atomicNumber, String symbol, String boilingPoint, String meltingPoint,
String density, String molecularWeight) {
this.name = name;
this.atomicNumber = atomicNumber;
this.symbol = symbol;
this.boilingPoint = boilingPoint;
this.meltingPoint = meltingPoint;
this.density = density;
this.molecularWeight = molecularWeight;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\n Element name: " + this.name);
builder.append("\n Atomic no: " + this.atomicNumber);
builder.append("\n Symobl : " + this.symbol);
builder.append("\n Boiling point : " + this.boilingPoint);
builder.append("\n Melting point : " + this.meltingPoint);
builder.append("\n Density : " + this.density);
builder.append("\n Molecular weight: " + this.molecularWeight);
return builder.toString();
}
}
And running the above code against the above two lines in the file, I get the following input:
Element name: actinium
Atomic no: 89
Symobl : Da
Boiling point : 3470
Melting point : 1926
Density : missing-x
Molecular weight: missing-y
Element name: actinium
Atomic no: 13
Symobl : Gk
Boiling point : 5480
Melting point : 1124
Density : missing-z
Molecular weight: missing-w
Use this
public static void readFileData(String filename) throws FileNotFoundException{
ArrayList<Element> list = new arrayList<>();
String split = ","; //split with comma
Scanner in = new Scanner(new File(filename));
String wordIn;
Element elem = new Element();
while (in.hasNextLine()) {
wordIn = in.nextLine();
String splitter[] = wordIn.split(split);
String name = splitter[0];
int atomicNumber = Integer.parseInt(splitter[1]);
String symbol = splitter[2];
String boilingPoint = splitter[3];
String meltingPoint = splitter[4];
String density = splitter[5];
String molecularWeight = splitter[6]
elem.setName(name);
elem.setAtomicNumber(atomicNumber);
elem.setSymbol(symbol);
elem.setBoilingPoint(boilingPoint);
elem.setMeltingPoint(meltingPoint);
elem.setDensity(density);
elem.setMolecularWeight(molecularWeight);
list.add(elem);
}
for(Element el : list){
sout(el.toString()) // if you have a to string method
}
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
String file = sc.next();
readFileData(file);
}
Make sure you have those setters in your Element class. And a too String method would be handy but not necessary. If the variable is type int in your Element class the you can do Integer.parseInt() or Double.parseDouble which converts string to integer or float etc. sout is short for System.out.println(); type sout + tab and you get the full thing.

Extracting from a string array in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm making a game where the user enters his/her first name and last name. The program extracts the first letters from the names, then outputs names from a string array.
I'm thinking the issue is in the last part of the code, where I'm comparing the Strings firstletter and lastLetter to the array. But I'm not sure. I have spent some time researching, and I'm stuck.
Any comments welcome. You won't hurt my feelings.
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
public abstract class ChristmasName extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("What is your Christmas Name?");
frame.setVisible(true);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JLabel firstName = new JLabel("First name:");
JTextField first = new JTextField(15);
JLabel lastName = new JLabel("Last name:");
JTextField last = new JTextField(15);
panel.add(firstName);
panel.add(first);
panel.add(lastName);
panel.add(last);
JButton submit = new JButton("Submit");
panel.add(submit);
submit.addActionListener(new ActionListener() {
#Override
public actionPerformed(ActionEvent e) {
String[] first_name = {"Apple","Eggnogg","Candy","Jingle","Holly","Goldie","Ho Ho","Frosty","Joyous","Mittens","Tinsel","Turkey","Tiny","Cranberry","Bloated","Angel","Bauble","Bulb","Ginger","Blitzen","Eve","Faith","Fruitcake","Goose","Glitter","Grinch"};
String[] last_name = {"Tidings","Swan","Jolly","Claus","Mistletoe","Punch","Chimney","Coal","Igloo","Jumper","Myrhh","Pudding","Reindeer","Rejoice","Icicle","Midnight","Shepherd","Surprise","Gift","Magi","Train","Tree","White","Donkey","Wreath","Stuffing"};
String firstLetter = first.getText();
firstLetter = firstLetter.substring(0,1);
String lastLetter = last.getText();
lastLetter = lastLetter.substring(0,1);
if (firstLetter == "A") {
firstLetter = first_name[0];
}
JOptionPane.showMessageDialog(null, firstLetter + " " + lastLetter);
System.exit(0);
}
});
}
}
Because you only need one character, you should use charAt() instead of substring. Although substring is possible, I always forget which parameter is inclusive or exclusive. I think you will too.
You should declare 2 chars:
char firstChar = first.getText().charAt(0);
char lastChar = last.getText ().charAt (0);
And then you can check them:
if (firstChar == 'A') { //Remember to use single quotes!
Not sure what you're asking but the first problem I see in your code is:
if (firstLetter == "A") {
firstLetter = first_name[0];
}
See the following on how to check if two strings have the same value:
How do I compare strings in Java?
Here's my solution for your problem:
String[] first_names = {"Apple","Eggnogg","Candy","Jingle","Holly","Goldie","Ho Ho","Frosty","Joyous","Mittens","Tinsel","Turkey","Tiny","Cranberry","Bloated","Angel","Bauble","Bulb","Ginger","Blitzen","Eve","Faith","Fruitcake","Goose","Glitter","Grinch"};
String[] last_names = {"Tidings","Swan","Jolly","Claus","Mistletoe","Punch","Chimney","Coal","Igloo","Jumper","Myrhh","Pudding","Reindeer","Rejoice","Icicle","Midnight","Shepherd","Surprise","Gift","Magi","Train","Tree","White","Donkey","Wreath","Stuffing"};
// User Input:
// Note: converted to lower case so the chars can be compared easily.
String firstName = first.getText().toLowerCase();
String lastName = last.getText().toLowerCase();
// Vars for output:
String sChristmasFirstName = null;
String sChristmasLastName = null;
// Do first name (if entered)
if(firstName.length() > 0){
// Loop all names to find the match:
for(String name : first_names){
if(name.toLower().charAt(0) == firstName.charAt(0)){
// We found a Christmas first name for the user
sChristmasFirstName = name;
// we can now exit the loop
break;
}
}
} // else, the user left this field blank
// Do same thing for last name
if(firstName.length() > 0){
// Loop all names to find the match:
for(String name : last_names){
if(name.toLower().charAt(0) == lastName.charAt(0)){
// We found a Christmas last name for the user
sChristmasLastName = name;
// we can now exit the loop
break;
}
}
} // else, the user left this field blank
// Prepare output string:
String output = "";
String outputErrorPortion = "";
if(sChristmasFirstName != null){
output += sChristmasFirstName;
}else{
if(firstName.length() == 0){
outputErrorPortion += "It looks like you didn't enter a first name.";
}else{
// Could not find an applicable first name
output += firstName;
ouputErrorPortion += "It looks like we couldn't find a Christmas first name for you :-(";
}
}
if(sChristmasLastName != null){
output += " " + sChristmasLastName;
}else{
if(lastName.length() == 0){
outputErrorPortion += " It looks like you didn't enter a last name.";
}else{
// Could not find an applicable last name
output += " " + lastName;
ouputErrorPortion += " It looks like we couldn't find a Christmas last name for you :-(";
}
}
// trim leading and trailing spaces if there are any:
output = output.trim();
outputErrorPortion = outputErrorPortion.trim();
// Variable 'output' now contains the Christmas first name, last name, both, or neither.
// Error message now contains a descriptive error about what happened (if anything)
The string comparisons to choose the Christmas names occurs in a for each loop which loops over the first_names and last_names String arrays to find the first match that starts with the same letter as the user's inputted first and last names. The Christmas names are then concatenated at the end to the output variable with the user's inputted first and/or last names being used in place of the Christmas equivalent if a relevant entry could not be found in the arrays of Christmas names. An error message is also constructed in the outputErrorPortion variable if any errors occurred while processing to names.
Here is the code you need read it carefully:
String[] firstNames = { "Apple", "Eggnogg", "Candy", "Jingle", "Holly", "Goldie", "Ho Ho", "Frosty","Joyous", "Mittens", "Tinsel", "Turkey", "Tiny", "Cranberry", "Bloated", "Angel", "Bauble","Bulb", "Ginger", "Blitzen", "Eve", "Faith", "Fruitcake", "Goose", "Glitter", "Grinch" };
String[] lastNames = { "Tidings", "Swan", "Jolly", "Claus", "Mistletoe", "Punch", "Chimney", "Coal","Igloo", "Jumper", "Myrhh", "Pudding", "Reindeer", "Rejoice", "Icicle", "Midnight", "Shepherd","Surprise", "Gift", "Magi", "Train", "Tree", "White", "Donkey", "Wreath", "Stuffing" };
// ArrayLists will contain the matching items
ArrayList<String> firstNamesMatching = new ArrayList<String>();
ArrayList<String> lastNamesMatching = new ArrayList<String>();
// Check which names from firstNames matching the firstLetter
String firstLetter = first.getText().substring(0, 1).toUpperCase();
for (String s : firstNames) {
if (s.startsWith(firstLetter))
firstNamesMatching.add(s);
}
// Check which names from lastNames matching the lastLetter
String lastLetter = last.getText().substring(0, 1).toUpperCase();
for (String s : lastNames) {
if (s.startsWith(lastLetter))
lastNamesMatching.add(s);
}
JOptionPane.showMessageDialog(null, firstNamesMatching.toArray() + " " + lastNamesMatching);
Also:
Although the arrays firstNames and lastNames and etc have to be outside the actionListener.You should have in mind the memory that your program use and not initialize the same things again and again.

How do you parse a difficult .txt file?

I'm fairly new to java and have been attempting to read a very difficult .txt file and input it into my MySQL DB.
To me, the file has some very weird delimiting rules. the delimiting seems to be all commas but other parts just do not make any sense. here is a few examples:
" "," "," "," "," "
" ",,,,,,," "
" ",0.00," "
" ",," ",," ",," "
What I do know is that all fields containing letters will be the normal ,"text", format.
all columns that only have numerals will follow this format: ,0.00, except for the first column which follows the normal format "123456789",
Then anything with no data will alternate between ,, or ," ",
I have been able to get the program to read correctly with java.sql.Statement but I need it to work with java.sql.PreparedStatement
I can get it to work with only a few columns selected but I need this to work with 100+ columns and some fields contain commas e.g. "Some Company, LLC"
Here is the code I currently have but I am at a loss as to where to go next.
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.*;
public class AccountTest {
public static void main(String[] args) throws Exception {
//Declare DB settings
String dbName = "jdbc:mysql://localhost:3306/local";
String userName = "root";
String password = "";
String fileName = "file.txt";
String psQuery = "insert into accounttest"
+ "(account,account_name,address_1,address_2,address_3) values"
+ "(?,?,?,?,?)";
Connection connect = null;
PreparedStatement statement = null;
String account = null;
String accountName = null;
String address1 = null;
String address2 =null;
String address3 = null;
//Load JDBC Driver
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("JDBC driver not found.");
e.printStackTrace();
return;
}
//Attempt connection
try {
connect = DriverManager.getConnection(dbName,userName,password);
}
catch (SQLException e) {
System.out.println("E1: Connection Failed.");
e.printStackTrace();
return;
}
//Verify connection
if (connect != null) {
System.out.println("Connection successful.");
}
else {
System.out.println("E2: Connection Failed.");
}
BufferedReader bReader = new BufferedReader(new FileReader(fileName));
String line;
//import file into mysql DB
try {
//Looping the read block until all lines in the file are read.
while ((line = bReader.readLine()) != null) {
//Splitting the content of comma delimited file
String data[] = line.split("\",\"");
//Renaming array items for ease of use
account = data[0];
accountName = data[1];
address1 = data[2];
address2 = data[3];
address3 = data[4];
// removing double quotes so they do not get put into the db
account = account.replaceAll("\"", "");
accountName = accountName.replaceAll("\"", "");
address1 = address1.replaceAll("\"", "");
address2 = address2.replaceAll("\"", "");
address3 = address3.replaceAll("\"", "");
//putting data into database
statement = connect.prepareStatement(psQuery);
statement.setString(1, account);
statement.setString(2, accountName);
statement.setString(3, address1);
statement.setString(4, address2);
statement.setString(5, address3);
statement.executeUpdate();
}
}
catch (Exception e) {
e.printStackTrace();
statement = null;
}
finally {
bReader.close();
}
}
}
Sorry if it's not formatted correctly, I am still learning and after being flustered for several days trying to figure this out, I didn't bother making it look nice.
My question is would something like this be possible with such a jumbled up file? if so, how do I go about making this a possibility? Also, I am not entirely familiar with prepared statements, do I have to declare every single column or is there a simpler way?
Thanks in advance for your help.
EDIT : To clarify what I need is I need to upload a txt file to a MySQL database, I need a way to read and split(unless there is a better way) the data based on either ",", ,,,,, ,0.00, and still keep fields together that have commas in the field Some Company, LLC. I need to do this with 100+ columns and the file varies from 3000 to 6000 rows. Doing this as a prepared statement is required. I'm not sure if this is possible but I appreciate any input anyone might have on the matter.
EDIT2 : I was able to figure out how to get the messy file sorted out thanks to rpc1. instead of String data[] = line.split("\",\""); I used String data[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); I still had to write out each variable to link it to the data[] then write out each statement.setString for each column as well as write the replaceALL("\"", ""); for each column but I got it working and I couldn't find another way to use prepared statements. Thank you for all your help!
You can cycles
for example:
String psQuery = "insert into accounttest"
+ "(account,account_name,address_1,address_2,address_3,..,adrress_n) values"
+ "(?,?,?,?,?,?,..,?)"; //you have to put m=n+2 values
.....
//you can change separator
String data[] = line.replace("\",\"",";").replace("\"","").split(";");
for(int i=0;i<m;i++)
{
if(i<data.length) //if index smaller then array siz
statement.setString(i+1, data[i]);
else
statement.setString(i+1, ""); //put null
}
statement.executeUpdate();
P.S. if your csv file large use batch insert (addBatch())
and use Pattern to split string
Pattern p = Pattern.compile(";","");
p.split(st);
EDIT
Try this split function
private static Pattern pSplit = Pattern.compile("[^,\"']+|\"([^\"]*)\"|'([^']*)'"); //set pattern as global var
private static Pattern pReplace = Pattern.compile("\"");
public static Object[] split(String st)
{
List<String> list = new ArrayList<String>();
Matcher m = pSplit.matcher(st);
while (m.find())
list.add( pReplace.matcher(m.group(0)).replaceAll("")); // Add .replace("\"", "") to remove surrounding quotes.
return list.toArray();
}
for example
intput string: st="\"1212\",\"LL C ,DDD \",\"CA, SPRINGFIELD\",232.11,3232.00";
split on 5 item array:
1212
LL C ,DDD
CA, SPRINGFIELD
232.11
3232.00
EDIT2
this example solves all your problems (even empty values)
private static Pattern pSplit = Pattern.compile(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
public static String[] split2(String st)
{
String[] tokens = pSplit.split(st);
return tokens;
}
I was able to figure out both issues that I was having by this little bit of code. Again, thanks for all of your help!
for (String line = bReader.readLine(); line != null; line = bReader.readLine()) {
//Splitting the content of comma delimited file
String data[] = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
//Iterating through the file and updating the table.
statement = connect.prepareStatement(psQuery);
for (int i =0; i < data.length;i++) {
temp = data[i];
temp = temp.replaceAll("\"", "");
statement.setString(i+1, temp);
}
statement.executeUpdate();
}

Categories