In: Computer Science
Create a Java class named ReadWriteCSV that reads the attached
cis425_io.txt file that you will save in your workspace as
src/cis425_io.txt and displays the following table:
--------------------------
| No | Month Name | Days |
--------------------------
| 1 | January | 31 |
| 2 | February | 28 |
| 3 | March | 31 |
| 4 | April | 30 |
| 5 | May | 31 |
| 6 | June | 30 |.
| 7 | July | 31 |
| 8 | August | 31 |
| 9 | September | 30 |
| 10 | October | 31 |
| 11 | November | 30 |
| 12 | December | 31 |
--------------------------
Write that file out in reverse order to a file named:
src/cis425_ior.txt
public class ReadWriteCSV {
// Put class properties here
// Add method, processInfile(), to open file and read here
void processInfile()
{
File filename = new File
("cis425_io.txt");
Scanner in = new
Scanner(System.in); // System.in is an InputStream
Scanner inFile = new
Scanner("cis425_io.txt");
}
// add method, displayTable(), here to display the table
void displayTable() {
}
// add method, writeOutfile(), here to open and write the data in
reverse order to the new file
void writeOutfile() {
}
// add main() method here
public static void main(String[] args) {
}
}
// For any doubt, feel free to comment.
CODE with Comments:-
package readwritecsv;
import java.io.*;
import java.util.*;
public class ReadWriteCSV {
//Arraylist which will store the src/cis425_io.txt details line
by line
static ArrayList<String> arr = new
ArrayList<String>();
static void processInfile() throws FileNotFoundException
{
File filename = new File ("src/cis425_io.txt");
Scanner in = new Scanner(System.in); // System.in is an
InputStream
Scanner inFile = new Scanner(filename);
//Reading till end of the file
while(inFile.hasNextLine()){
String line = inFile.nextLine();
//Adding line to arraylist
arr.add(line);
}
}
static void displayTable(){
System.out.println("--------------------------");
System.out.println("| No | Month Name | Days |");
System.out.println("--------------------------");
//Traversing through arraylist to print table
for(int i=0;i<arr.size();i++){
String line = arr.get(i);
//Split each line by space so that we get index,monthname,days
seperately
String[] words = line.split(" ");
System.out.println("| " + words[0] + " | " + words[1] + " | " +
words[2] + " |");
}
System.out.println("--------------------------");
}
static void writeOutfile() throws IOException{
//Opening file
FileWriter writer = new FileWriter("src/cis425_ior.txt");
BufferedWriter bw = new BufferedWriter(writer);
//Writing into file src/cis425_ior.txt by traversing the arraylist
reverse
for(int i=arr.size()-1;i>=0;i--){
bw.write(arr.get(i) + "\n");
}
bw.close();
}
public static void main(String[] args) throws
FileNotFoundException, IOException {
//Calling all function in a sync order
processInfile();
displayTable();
writeOutfile();
}
}
Code Snippets:-
Output:-