Link to home
Start Free TrialLog in
Avatar of Kennywen
Kennywen

asked on

Read and write csv file

Can i use the .csv file to store my address book information? If yes, how can i read and write the .csv files? What is the benefit of using .csv file than normal .txt file? Is't possible to make the .csv file is unreadable by user or do some encoding inside the .csv file?

thanks
Avatar of manifoldronin
manifoldronin

CSV stands for Comma Separated Values.  That's the only thing you need to know to be able to read and write one - in the end, they are little more than regular text files.
Anything you can/can't do to/with a text file you can/can't do to/with a csv file.
Avatar of Kennywen

ASKER

any other tool that allow us to store the address book information with the encoding or make the file is unreable by user?

thanks
But i don't want to use mysql or other databases.
You can use XML which supports encoding and structural query.  It still doesn't have any built-in feature to prevent particular users from reading it, but you can always set the access rights at the OS level, can't you?
Can u give me some example so that i can learn from it. BTW is't the XML support insert, delete update and select function and XML can be use in any OS?
beside XML can anyone show me how to read and write the .csv files.

thanks
Actually i undestand that i can use java.util.StringTokenizer to split the data when i want to read it but how can i write the data to the .csv file?
Avatar of CEHJ
You can encrypt any text file. Here's an example:

http://javaalmanac.com/egs/javax.crypto/PassKey.html


Writing to a csv file is as simple as writing any other file. Suppose you have each column value in an array called 'values':

// 'out' is a PrintWriter opened on a FileWriter, opened on a file
for(int i = 0;i < values.length - 1;i++) {
      out.print(values[i]);
      out.print(",")
}
out.println(values[values.length - 1]);

in your case, where 'values' appears in the print\println you'd want to call print(encrypt(values[i])) or whatever
should i write:

PrintWriter out = null;
for(int i = 0;i < values.length - 1;i++) {
     out.print(values[i]);
     out.print(",")
}
out.println(values[values.length - 1]);

But how can i specify the file name? If the file already exist with some data so the out.println(values[values.length - 1]); will overwrite the current data in the file? If yes, how can i append it ?

thanks
>>But how can i specify the file name?

PrintWriter out = new PrintWriter(new FileWriter("x.csv"));


>>how can i append it ?

PrintWriter out = new PrintWriter(new FileWriter("x.csv"), true);

>> PrintWriter out = new PrintWriter(new FileWriter("x.csv"), true);

if i put true then it will append additional data into the csv file? else it will just overwrite the current data in the csv file?

why at the end i should write out.println(values[values.length - 1]);

thanks
>>if i put true ...

Yes

>>why at the end...

Because you don't need a comma at the end of the line

then the csv file will contain information like :
Smith Joe, M, UK, 22
Smith Joe, M, UK, 22
Smith Joe, M, UK, 22

every new data will in the different row?

Can i count there is how many rows in the csv file?

thanks
The read file:

int counter=0;

BufferedReader buf = new BufferedReader(new FileReader(new File("data.csv);
            while ( (text = buf.readLine()) != null) {
               String split = line.split(",");
               >> how can i put the two dimensional array in here?
               counter++;
            }

thanks


>>every new data will in the different row?

>>Can i count there is how many rows in the csv file?

why would you want to do that btw?
SOLUTION
Avatar of johnknapp
johnknapp

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> why would you want to do that btw?

i want to count there is how many rows in the files so that i can create a two dimensional array.
I want to create two dimensional array like;
private Object[][] data = {
            {"Mary", "Campione",
             "Snowboarding", new Integer(5), new Boolean(false)},
            {"Alison", "Huml",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath",
             "Knitting", new Integer(2), new Boolean(false)},
            {"Sharon", "Zakhour",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Philip", "Milne",
             "Pool", new Integer(10), new Boolean(false)}
        };
Please show me how to read the file and assign it to two dimensional array like:
private Object[][] data = {
            {"Mary", "Campione",
             "Snowboarding", new Integer(5), new Boolean(false)},
            {"Alison", "Huml",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath",
             "Knitting", new Integer(2), new Boolean(false)},
            {"Sharon", "Zakhour",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Philip", "Milne",
             "Pool", new Integer(10), new Boolean(false)}
        };


my sample file:
BufferedReader buf = new BufferedReader(new FileReader(new File("data.csv);
            while ( (text = buf.readLine()) != null) {
               String split = line.split(",");
               >> how can i put the two dimensional array in here?
               counter++;
            }

thanks
>>  if (i + i < fields.length)
You probably mean :
    if (i + 1 < fields.length)

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Replace :
           BufferedReader buf = new BufferedReader(new FileReader(new File("data.csv);
By :
           BufferedReader buf = new BufferedReader(new FileReader("data.csv"));
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How can i update and delete the information in the csv file?

thanks
Is't possible to perform update and delete in the csv file without using sql statement?

thanks
is't possible just delete a specify line in the csv file?
It the csv file is not that large why not cache it all in memory and then rewrite it when you are finished modifying it,

and why would you be using a SQL statement?
>> why would you be using a SQL statement?

because i just afraid i cannot delete or update the csv file without using sql statement.
I guess the question is what exactly are you trying to achieve by using a CSV file?  What data and how much of it are you trying to store.  CSV Files are really designed for quick write and read not really for modifications.  The strong point about using csv is easy implementation, for more sophisticated operations on files I would recommend possibly keeping an index into the file stored separately - a record, byte location kind of key file and then make sure modifications to the csv file always happen through the same interface to make sure the index stays correct with the file.
I am not sure if the scope of your original question has changed, and I am still unclear as to how you would even use a SQL query to perform an operation on a CSV file . . . are you using a JDBC driver that operates on CSV files?

Which I have never heard of myself.

If you want to change a CSV file and then save it and it is not a huge file, say under 10,000 records or so try something like this . . .

1) read file into 2 dimensional object array (is that the data type you want to use?)

2) modify the elements accordingly

3) rewrite the file, ie open the file writer with ...
FileWriter fileWriter = new FileWriter("somecsvfile.csv", false); // so as to completely write over the existing file

4) reiterate over you modified object array and write out each element.
Object[][] some2dArray; // initialized elsewhere, say an array of strings for sake of example
BufferedWriter writer = new BufferedWriter(fileWriter); // since this will give us easy string processing
for (int i = 0; i < some2dArray.length; i++) {
    for (int inner = 0; inner < some2dArray[i].length; inner++) {
        writer.write(some2dArray[i][inner].toString());
        if (inner + 1 < some2dArray[i].length)
            writer.write(",");
        else
            writer.write(System.getProperty("line.separator", "\n"));
    }
}
writer.flush();
writer.close();

// handle all IOExceptions omitted for clarity
So i need to write the csv file to some2dArray first and then change the value (if user press the edit button) or delete the value (if user press delete button) and then write it into the file again?

thanks
Sort of,

The user will be operating on the array for some amount of time correct? When the user is finished this is when you commit the changes to the file.

So this way (I am assuming this is kind of what you were talking about in pseudo-pseudo code)

1) User opens program component

2) Load the file into a 2d object array or whatever data structure you feel is appropriate

3) User clicks edit button or delete button

4) Modify array

5) User repeats process 3 n times, each time your code repeats 4 n times

6) User finishes editing

7) resave file
No, i will not load the file into a 2d object array when user run the program.
The csv file is to keep the address book information. so when the user press edit button then a pop up window will display then the user can edit it. once the user press ok button then i will  Load the file into a 2d object array.

Can i use the above approach?

thanks
Object[] data = new Object[3];
data[0] = new String(nameField.getText());
data[1] = new String(mobileField.getText());
data[2] = new String(emailField.getText());

PrintWriter out = new PrintWriter(new FileWriter("phone.csv"), true);
for(int i = 0;i < data.length - 1;i++) {
      out.print(data[i]);
      out.print(",");
}
out.println(data[data.length - 1]);

The above code will not append the file. why?
i get the answer, i should use:

PrintWriter out = new PrintWriter(new BufferedWriter( new FileWriter ("phone.csv", true)));

one quick thing with your sample code,

Make sure if your data has any possibility of ever having a comma embedded in the field (seems unlikely in your case unless the name field is last,first)

to wrap the data in quotes
such as
"name","mobile","email"
"name2","mobile2","email2"

otherwise you will have troubles reading it (but only in the case that your data could contain embedded commas)
Object[][] data = new Object[counter][3];
            BufferedReader buf1 = new BufferedReader(new FileReader("phone.csv"));
            counter=0;
            while ( (text = buf1.readLine()) != null) {
               text=text.trim();
               if (text.length()==0)  continue; // empty line
               String[] split = text.split(",");
               for (int j=0;j<5;j++) // for each field:
               {
                   switch(j)
                   {
                       //case 3: data[counter] = new Integer(text); break;
                       //case 4: data[counter] = new Boolean(text); break;
                       default: data[counter] = split[j]; break;
                           }
               }
                counter++;
            }

an error occur:
BoxAlignmentDemo.java:588: incompatible types
found   : java.lang.String
required: java.lang.Object[]
default: data[counter] = split[j]; break;
                                         ^
1 error
Replace :
  data[counter] =
By :
  data[counter][j] =
You can't assign a string to an object array reference

you should do

data[counter][j] = split[j];

or in context

default: data[counter][j] = split[j]; break;

try that, but why the switch (j) if you aren't using the switch construct for what it is useful for?
You can use a class like this to add/delete lines in a csv file. e.g.:

StringList sl = new StringList("your.csv");
sl.remove(1); // remove first line after column headers





SNIP==================================

import java.io.*;
import java.util.ArrayList;

  public class StringList extends ArrayList {

  public StringList() {
    super();
  }

  public StringList(String fileName) {
    this();
    String line = null;
    BufferedReader in = null;
    try {
      in = new BufferedReader(new FileReader(fileName));
      while ((line = in.readLine()) != null) {
        add(line);
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    finally {
      try {
        in.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}
thanks to all
8-)
There's a few jdbc drivers that you can use rather than such a low level solution.
For read-only, I've had good success with csvjdbc.jar. There are a few of them at sourceforge.

HTH - rich