File Input and Output to a CSV file from an Array

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 1250 Views - Last Post: 09 November 2020 - 05:30 AM Rate Topic: -----

#1 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 01:51 PM

So out of the 5 labs I only had issues with the last 2. I would have preferred to write the whole thing by myself, then I wouldn't have had so many issues. But hard to do these when you cannot step through what you didn't write. This one I am having a lot of issues with because I am new to writing to files. The instructions are as follows:
A comma separated value (.csv) file has been included to be used for this program. Each line contains two values, a name and a number separated by a comma (except the first line, which contains the titles for the value types). The name is that of a writer and the number refers to the number of works the writer has written. Ex. Jane Austen,6. Each line is an entry and each entry number can be updated by identifying the associated name.

Once complete, the following program opens data file allWorks.csv and asks if the user wants to update entries or add new entries. All entries are stored in an array while being read in and updated. The program then writes the array to the file, overwriting the original contents. The following TODO sections must be completed.

Open allWorks.csv for reading/input.
Locate an entry to be updated by name (use the Java String indexOf() method)
Add a new entry if the name isn't found in the file (give the entry a new number)
Open file allWorks.csv for output
Write contents of the array to allWorks.csv (original file is overwritten)
Ex: If the input is:

y
J.K. Rowling
30
y
Elton John
y
62
n
and allWorks.csv originally contains:

Name,Number of Novels
Jane Austen,6
Charles Dickens,20
Ernest Hemingway,9
Jack Kerouac,22
F. Scott Fitzgerald,8
Mary Shelley,7
Charlotte Bronte,5
Mark Twain,11
Agatha Christie,73
Ian Flemming,14
J.K. Rowling,14
Stephen King,54
Oscar Wilde,1
the output in allWorks.csv is:

Name,Number of Novels
Jane Austen,6
Charles Dickens,20
Ernest Hemingway,9
Jack Kerouac,22
F. Scott Fitzgerald,8
Mary Shelley,7
Charlotte Bronte,5
Mark Twain,11
Agatha Christie,73
Ian Flemming,14
J.K. Rowling,30
Stephen King,54
Oscar Wilde,1
Elton John,62

The original code is:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataFile {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      FileInputStream inputFileStream = null; // File input stream
      Scanner inFS = null;                    // File Scanner object 
      
      FileOutputStream outputFileStream = null;
      PrintWriter outFS = null;

      String lineString = "";                 // Stores line-by-line input from file
      char yesNo = 'n';
      String updateName = "";
      String updateNum = "";

      String[] fileContents = new String[50]; // Array for storing and updating file contents
      int size = 0;
      int i = 0;
      boolean entryFound = false;

      System.out.println("Would you like to update allWork.csv?");
      yesNo = scnr.next().charAt(0);
      scnr.nextLine();

      while (yesNo == 'y') {
         size = 0;
         // TODO: Open file "allWorks.csv" for input

         System.out.println("Which entry would you like to update?");
         updateName = scnr.nextLine();
   
         while (inFS.hasNext()) {
            lineString = inFS.nextLine();
                     
            if(/* TODO: Locate updateName in the file */) {
               entryFound = true;
               System.out.println("Enter a new value for " + updateName);
               updateNum = scnr.next();
               lineString = updateName + "," + updateNum;
            }

            // Storing each line in the array
            fileContents[size] = lineString;
            ++size;
         }

         
         if (!entryFound) {
            System.out.println("Entry not found. Add new entry?");
            yesNo = scnr.next().charAt(0);
            scnr.nextLine();

            if(yesNo == 'y') {
               System.out.println("Number of works?");
               // TODO: Add new entry if the name isn't found in the file
            }
         }

         // TODO: Open file "allWorks.csv" for output
         
         // TODO: Write contents of the array to the allWorks.csv (original file is overwritten)
         

         System.out.println("Would you like to continue to update allWork.csv?");
         yesNo = scnr.next().charAt(0);
         scnr.nextLine();
      }

      outputFileStream.close(); // close() may throw IOException if fails 
   }     
}



What I have done so far:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataFile {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      FileInputStream inputFileStream = null; // File input stream
      Scanner inFS = null;                    // File Scanner object 
      
      FileOutputStream outputFileStream = null;
      PrintWriter outFS = null;

      String lineString = "";                 // Stores line-by-line input from file
      char yesNo = 'n';
      String updateName = "";
      String updateNum = "";

      String[] fileContents = new String[50]; // Array for storing and updating file contents
      int size = 0;
      int i = 0;
      boolean entryFound = false;

      System.out.println("Would you like to update allWork.csv?");
      yesNo = scnr.next().charAt(0);
      scnr.nextLine();

      while (yesNo == 'y') {
         size = 0;
         // TODO: Open file "allWorks.csv" for input
         inputFileStream = new FileInputStream ("allWorks.csv");
         
         System.out.println("Which entry would you like to update?");
         updateName = scnr.nextLine();
   
         while (inFS.hasNext()) {
            lineString = inFS.nextLine();
                     
            if(updateName.indexOf(lineString, 0) > 0) {
               entryFound = true;
               System.out.println("Enter a new value for " + updateName);
               updateNum = scnr.next();
               lineString = updateName + "," + updateNum;
            }

            // Storing each line in the array
            fileContents[size] = lineString;
            ++size;
         }

         
         if (!entryFound) {
            System.out.println("Entry not found. Add new entry?");
            yesNo = scnr.next().charAt(0);
            scnr.nextLine();

            if(yesNo == 'y') {
               System.out.println("Number of works?");
               // TODO: Add new entry if the name isn't found in the file
               fileContents[-1] = updateName + ", " + updateNum;
            }
         }

         // TODO: Open file "allWorks.csv" for output
         outputFileStream = new FileOutputStream ("allWorks.csv"); 
         // TODO: Write contents of the array to the allWorks.csv (original file is overwritten)
         outputFileStream.writeNext(fileContents);

         System.out.println("Would you like to continue to update allWork.csv?");
         yesNo = scnr.next().charAt(0);
         scnr.nextLine();
      }

      outputFileStream.close(); // close() may throw IOException if fails 
   }     
}



I don't understand how to open a csv file, append the new entry to an array (but I may have it right), and finally rewrite the csv file with the new data. I am not asking you to write this but help me understand the 3 points. Thank you.

This post has been edited by mcamardo: 08 November 2020 - 01:53 PM


Is This A Good Question/Topic? 0
  • +

Replies To: File Input and Output to a CSV file from an Array

#2 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 6,509
  • Joined: 25-December 13

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 01:59 PM

Quote

I don't understand how to open a csv file,

It depends if the data in the csv file has fields enclosed in "s that could contain the cvs file's delimiter or the newline character.
If the csv is simple enough (no newline characters), it can be read by Scanner class's nextLine method.

Quote

append the new entry to an array

Use the String class's split method to separate the columns of the csv.

If the data for a row is held in an array, a row for the csv file could be built by concatenating the elements of the array separated by the csv character: ar[0] + "," + ar[1] ....
The String that was build by the above would then be written to a file, say with the PrintWriter class.
Was This Post Helpful? 1
  • +
  • -

#3 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 02:15 PM

The csv file is split via a comma and the pre-entered code has nextline and Printwriter it seems. So would the output go out as say a while loop having outFS.fileContents[i]; as the output?
Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 6,509
  • Joined: 25-December 13

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 02:23 PM

The output statement would be in a for loop that iterates through the rows of the array.
The record to write would be built by concatenating as described above and then written.
Was This Post Helpful? 1
  • +
  • -

#5 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 02:35 PM

fileContents[-1] = updateName;
fileContents[-1] = updateNum;


Would that work to send to the last open spot on the array? The array is set to 50 but only 14 are filled.


for (int c = 0; c < fileContents.length; c++) {
        	 outFS.append(fileContents[i] + "," + fileContents[i + 1]);
        	 c = c + 2;
         }



So would this be a good way to export each line to output to the csv?

This post has been edited by mcamardo: 08 November 2020 - 02:37 PM

Was This Post Helpful? 0
  • +
  • -

#6 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 6,509
  • Joined: 25-December 13

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 02:47 PM

I use the println method of the PrintWriter class to write simple text files.
Was This Post Helpful? 1
  • +
  • -

#7 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 03:06 PM

Updated code. But when I try to update one thing it never moved on.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataFile {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      FileInputStream inputFileStream = new FileInputStream("allWorks.csv"); // File input stream
      Scanner inFS = new Scanner(System.in);                    // File Scanner object 
      
      FileOutputStream outputFileStream = null;
      PrintWriter outFS = null;

      String lineString = "";                 // Stores line-by-line input from file
      char yesNo = 'n';
      String updateName = "";
      String updateNum = "";

      String[] fileContents = new String[50]; // Array for storing and updating file contents
      int size = 0;
      int i = 0;
      boolean entryFound = false;

      System.out.println("Would you like to update allWork.csv?");
      yesNo = scnr.next().charAt(0);
      scnr.nextLine();

      while (yesNo == 'y') {
         size = 0;
         // TODO: Open file "allWorks.csv" for input
         inputFileStream.read();
         
         System.out.println("Which entry would you like to update?");
         updateName = scnr.nextLine();
   
         while (inFS.hasNext()) {
            lineString = inFS.nextLine();
                     
            if(updateName.indexOf(lineString, 0) > 0) {
               entryFound = true;
               System.out.println("Enter a new value for " + updateName);
               updateNum = scnr.next();
               lineString = updateName + "," + updateNum;
            }

            // Storing each line in the array
            fileContents[size] = lineString;
            ++size;
         }

         
         if (!entryFound) {
            System.out.println("Entry not found. Add new entry?");
            yesNo = scnr.next().charAt(0);
            scnr.nextLine();

            if(yesNo == 'y') {
               System.out.println("Number of works?");
               // TODO: Add new entry if the name isn't found in the file
               fileContents[-1] = updateName;
               fileContents[-1] = updateNum;
            }
         }

         // TODO: Open file "allWorks.csv" for output
         outputFileStream = new FileOutputStream ("allWorks.csv"); 
         // TODO: Write contents of the array to the allWorks.csv (original file is overwritten)
         for (int c = 0; c < fileContents.length; c++) {
        	 outFS.println(fileContents[i] + "," + fileContents[i + 1]);
        	 c = c + 2;
         }

         System.out.println("Would you like to continue to update allWork.csv?");
         yesNo = scnr.next().charAt(0);
         scnr.nextLine();
      }
      inputFileStream.close();
      outputFileStream.close(); // close() may throw IOException if fails 
   }     
}


Was This Post Helpful? 0
  • +
  • -

#8 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 6,509
  • Joined: 25-December 13

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 03:23 PM

Quote

when I try to update one thing it never moved on.

Please explain and give some details about it.
Was This Post Helpful? 1
  • +
  • -

#9 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 03:39 PM

Oops sorry.
 System.out.println("Which entry would you like to update?");
         updateName = scnr.nextLine(); 
It doesn't move past this when you enter the data.
Was This Post Helpful? 0
  • +
  • -

#10 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 6,509
  • Joined: 25-December 13

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 03:43 PM

Where is the code that reads from the csv file? I see two Scanner class objects that read from System.in
Should one of those be reading from the file?
Was This Post Helpful? 1
  • +
  • -

#11 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 04:07 PM

Oops you are correct. There I updated it.

import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataFile {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      FileInputStream inputFileStream = new FileInputStream("allWorks.csv"); // File input stream
      Scanner inFS = new Scanner("allWorks.csv"); // File Scanner object 
      
      FileOutputStream outputFileStream = new FileOutputStream("allWorks.csv");
      PrintWriter outFS = new PrintWriter("allWorks.csv");

      String lineString = "";  // Stores line-by-line input from file
      char yesNo = 'n';
      String updateName = "";
      String updateNum = "";

      String[] fileContents = new String[50]; // Array for storing and updating file contents
      int size = 0;
      int i = 0;
      boolean entryFound = false;

      System.out.println("Would you like to update allWork.csv?");
      yesNo = scnr.next().charAt(0);
      scnr.nextLine();

      while (yesNo == 'y') {
         size = 0;
         // TODO: Open file "allWorks.csv" for input
         inputFileStream.read();
         
         System.out.println("Which entry would you like to update?");
         updateName = scnr.nextLine();
   
         while (inFS.hasNext()) {
            lineString = inFS.nextLine();
                     
            if(updateName.indexOf(lineString, 0) > 0) {
               entryFound = true;
               System.out.println("Enter a new value for " + updateName);
               updateNum = scnr.next();
               lineString = updateName + "," + updateNum;
            }

            // Storing each line in the array
            fileContents[size] = lineString;
            ++size;
         }
         inputFileStream.close();
         
         if (!entryFound) {
            System.out.println("Entry not found. Add new entry?");
            yesNo = scnr.next().charAt(0);
            scnr.nextLine();

            if(yesNo == 'y') {
               System.out.println("Number of works?");
               // TODO: Add new entry if the name isn't found in the file
               fileContents[-1] = updateName;
               fileContents[-1] = updateNum;
            }
         }

         // TODO: Open file "allWorks.csv" for output
         outputFileStream = new FileOutputStream ("allWorks.csv"); 
         // TODO: Write contents of the array to the allWorks.csv (original file is overwritten)
         for (int c = 0; c < fileContents.length; c++) {
        	 outFS.println(fileContents[i] + "," + fileContents[i + 1]);
        	 c = c + 2;
         }

         System.out.println("Would you like to continue to update allWork.csv?");
         yesNo = scnr.next().charAt(0);
         scnr.nextLine();
      }

      outputFileStream.close(); // close() may throw IOException if fails 
   }     
}



I moved the inputFileStream.close() to after it is read. I realized I still had the file open and I closed it. But it is cycling through now but not finding J.K. Rowling which is in the csv file.

This post has been edited by mcamardo: 08 November 2020 - 04:13 PM

Was This Post Helpful? 0
  • +
  • -

#12 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 04:17 PM

Hmm it wipes out the data file completely.
Was This Post Helpful? 0
  • +
  • -

#13 g00se   User is online

  • D.I.C Lover
  • member icon

Reputation: 3729
  • View blog
  • Posts: 17,048
  • Joined: 20-September 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 04:39 PM

Quote

      // TODO: Open file "allWorks.csv" for input
            inputFileStream.read();



What's going on there?

btw, you have two Scanners open on stdin. Only one should be used
Was This Post Helpful? 1
  • +
  • -

#14 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 854
  • View blog
  • Posts: 6,509
  • Joined: 25-December 13

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 04:46 PM

Read the API doc for the Scanner class. The code on line 12 passes a String to the Scanner class's constructor.
You need to pass a File object to the constructor.

Quote

it wipes out the data file completely.

The PrintWriter class's constructor does that. Don't call the constructor until all the records have been read from the file.

This post has been edited by NormR: 08 November 2020 - 05:10 PM

Was This Post Helpful? 1
  • +
  • -

#15 mcamardo   User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 64
  • Joined: 29-June 08

Re: File Input and Output to a CSV file from an Array

Posted 08 November 2020 - 07:19 PM

// TODO: Open file "allWorks.csv" for input
         inputFileStream.read();


Is there another way to open the file? I thought I already did that with the code below:

FileInputStream inputFileStream = new FileInputStream("allWorks.csv");




Wouldn't I need a scanner for the input and a scanner to read the info from the file? I updated the code a little to call the scanners before they are used. I am seeing that my search is not finding data that is already there.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataFile {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      FileInputStream inputFileStream = null; // File input stream
      Scanner inFS = null; // File Scanner object 
      
      FileOutputStream outputFileStream = null;
      PrintWriter outFS = null;

      String lineString = "";  // Stores line-by-line input from file
      char yesNo = 'n';
      String updateName = "";
      String updateNum = "";

      String[] fileContents = new String[50]; // Array for storing and updating file contents
      int size = 0;
      int i = 0;
      boolean entryFound = false;

      System.out.println("Would you like to update allWork.csv?");
      yesNo = scnr.next().charAt(0);
      scnr.nextLine();

      while (yesNo == 'y') {
         size = 0;
         // TODO: Open file "allWorks.csv" for input
         inputFileStream = new FileInputStream("allWorks.csv");
         inFS = new Scanner("allWorks.csv");
         System.out.println("Which entry would you like to update?");
         updateName = scnr.nextLine();
   
         while (inFS.hasNext()) {
            lineString = inFS.nextLine();
                     
            if(updateName.contains(lineString)) {
               entryFound = true;
               System.out.println("Enter a new value for " + updateName);
               updateNum = scnr.next();
               lineString = updateName + "," + updateNum;
            }
            // Storing each line in the array
            fileContents[size] = lineString;
            ++size;
         }
         
         if (!entryFound) {
            System.out.println("Entry not found. Add new entry?");
            yesNo = scnr.next().charAt(0);
            scnr.nextLine();

            if(yesNo == 'y') {
               System.out.println("Number of works?");
               updateNum = scnr.next();
               // TODO: Add new entry if the name isn't found in the file
               fileContents[fileContents.length - 1] = updateName;
               fileContents[fileContents.length - 1] = updateNum;
            }
         }

         // TODO: Open file "allWorks.csv" for output
         outputFileStream = new FileOutputStream ("allWorks.csv"); 
         outFS = new PrintWriter("allWorks.csv");

         // TODO: Write contents of the array to the allWorks.csv (original file is overwritten)
         for (int c = 0; c < fileContents.length; c++) {
        	 outFS.println(fileContents[i] + "," + fileContents[i + 1]);
        	 c = c + 2;
         }

         System.out.println("Would you like to continue to update allWork.csv?");
         yesNo = scnr.next().charAt(0);
         scnr.nextLine();
      }
      inputFileStream.close();
      outputFileStream.close(); // close() may throw IOException if fails 
   }     
}




So on line 42 my if statement doesn't work. It is supposed to check the array for the entered string.

if(updateName.contains(lineString)) {

This post has been edited by mcamardo: 08 November 2020 - 07:45 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2