0

The goal of my code is to replace a certain text value within my .CSV file with the user input of a text field.

My .CSV file has values delimited by commas: hey,hi. If I'm just wanting to replace 'hey' then I would gather the input from the text field and replace 'hey' with 'bye'. Output: bye,hi.

In my code, I believe I am reading in my file and writing the contents of the file to a list, delimited by commas.

I will then iterate through the list and replace an instance of the user input within the list, with another user input and write it back to file.

However, I cannot write it back to file as I'm getting the Object[] cannot be converted to String[] error. Thus I'm stuck as to how to replace the instance of user input within the text file.

Here's my code:

try{

        //Convert user input into strings
        String strSerial = editSerialField.getText();
        String strLocation = editLocationField.getText();

        //Read existing file
        CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
        List myEntries = reader.readAll();

        //Iterate through my array
        for (int i = 0; i < myEntries.size(); i++)
        {
            //If an entry matches the user input
            if (myEntries.get(i).equals(strSerial))
            {
                //Set the match to the user input from strLocation
                myEntries.set(i, strLocation);
                break;
            }
        }

        //Write to existing file
        CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',');

        //Error is here**********************
        //Write the new string with the replaced word OVER the same file
        writer.writeNext(myEntries.toArray(new String[myEntries.size()]));
        writer.close();

        }catch (IOException e)
        {
            System.out.println(e);
        }
}

How do I modify my code so that it writes my changes to the .CSV file?

juiceb0xk
  • 949
  • 3
  • 19
  • 46

2 Answers2

0

For a start writeNext will write on line at a time, so you need to loop.

Secondly consider using not a raw List but using generics.

Thirdly, it may be cleaner to write as you go

and lastly, each line will contain an Array of Strings

consider this code (not tested)

        CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
        List<String []> myEntries = reader.readAll();
        reader.close ();

        CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',');

        //Iterate through my array
        for (String [] line : myEntries)
        {
            ArrayList<String> newLine = new ArrayList <String>();
            for (String word : line) {
            {
                String newVal = word.replace(strSerial, strLocation);
                newLine.add (newVal);
            }
            writer.writeNext(newLine.toArray(new String[newLine.size()]));
        }
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
  • This code doesn't work. It wipes my whole file - even if a user input was specified. – juiceb0xk Nov 10 '16 at 05:37
  • Are you closing the writer? `writer.close();` – Scary Wombat Nov 10 '16 at 05:41
  • I am now and it now outputs the user input in speech marks. It also wipes the whole file and only shows the user input. – juiceb0xk Nov 10 '16 at 05:43
  • I am glad that you have tried to undertsand the code I have provided to answer your question as to why `Object[] cannot be converted to String[]` I have not gone to the effort to debug your code or to even understand it fully. For example - which CSVWriter are you using? – Scary Wombat Nov 10 '16 at 05:50
  • I am using OpenCSV. I've put `writer.close` outside of the for loop and it does not overwrite the whole file anymore. But it does put every word into speech marks then places it all on one line. – juiceb0xk Nov 10 '16 at 05:54
  • @juiceb0xk Your question was about how to get past a compile error, and that's been solved. Since StackOverflow is a question-and-answer site and not a chat room, I don't think it's a good idea to start discussing a new, unrelated problem on this question. If you can't fix the problem yourself and need help, please post a new question. – ajb Nov 10 '16 at 05:57
  • This is what I am looking at http://opencsv.sourceforge.net/apidocs/com/opencsv/CSVWriter.html - the second parameter is whether the value should be quoted. – Scary Wombat Nov 10 '16 at 05:57
  • and of course please to accept and/or upvote this answer if it has been useful to you. – Scary Wombat Nov 10 '16 at 06:05
  • Thank you for your help. I have the quotation marks sorted. However, the text within the file all get formatted back to the first line. I will save this as a different question, as suggested by @ajb – juiceb0xk Nov 10 '16 at 06:07
  • check the eol char – Scary Wombat Nov 10 '16 at 06:08
  • @ScaryWombat "The CSVWriter that I looked at does not take a , as the second parameter" ... I'm looking at the same link you are, and the constructor does take `','` as a second parameter. `writeNext` is the method that needs a boolean as an optional second parameter, but it looks like OP was using the one-argument version. Unless there's an edit or a deleted comment I missed? – ajb Nov 10 '16 at 06:12
  • Sorry for bugging but I think this is too small of a problem to be asked in another question, which eol char should I be looking at? I've tried all I can and I still can't figure it out. – juiceb0xk Nov 10 '16 at 06:18
  • @ajb Thanks you are right and I am just getting confused. – Scary Wombat Nov 10 '16 at 06:20
  • @juiceb0xk Consider this post http://stackoverflow.com/questions/24400064/java-opencsv-writing-result-set-end-of-line-row – Scary Wombat Nov 10 '16 at 06:22
0

Your problem is/ starts at this line:

List myEntries = reader.readAll();

I assume that you did not noticed that the return type of the method readAll() is

  List<String[]> 

If for example your test file looks like :

hey, hi
hallo, hello
sth, sthelse

After calling readAll() your variable myEntries will be a list of string arrays; each array representing each row in your file and each string from that row as element of the array

myEntries :  [hey, hi]
             [hallo, hello]
             [sth, sthelse]

Keeping this in mind the next issue is

if (myEntries.get(i).equals(strSerial)) 

where you try to compare a String[] with a String which will not be true. Try it as follows :

try{
        //Convert user input into strings
        String strSerial = editSerialField.getText();
        String strLocation = editLocationField.getText();

        CSVReader reader = new CSVReader(new FileReader("test test.txt"), ',');
        // valid but not a good practice how you declare your variable before
        // List myEntries = reader.readAll();  // List of what??
        List<String[]> myEntries = reader.readAll();

        for (String[] row : myEntries){         // go through each array from your list representing a row in your file
            for (int i = 0; i < row.length; i++){       //go through each element of that array
                if (row[i].equalsIgnoreCase(strSerial)){
                    row[i] = strLocation;
                }
            }
        }

        //add the parameter CSVWriter.NO_QUOTE_CHARACTER to prevent opencsv from writing quotes to file
        CSVWriter writer = new CSVWriter(new FileWriter("test test.txt"), ',',CSVWriter.NO_QUOTE_CHARACTER);
        for (String[] row : myEntries){
            writer.writeNext(row);
        }        
        writer.close();
    }catch (IOException e){
        System.out.println(e);
    }

Not really important but i would prefer test.csv instead of test.txt as file name as long as you store comma-separated values in there.

Eritrean
  • 15,851
  • 3
  • 22
  • 28