In: Computer Science
I/O Lab Java
Purpose
To practice the input and output concepts discussed in this module. Specifically, reading from and writing to local files, and formatting output.
Instructions
Read in file input.csv and generate a cleanly formatted table in output.txt. See the samples below.
input.csv
name,ID,salary,years experience foo,1,13890,12 bar,2,2342,3 baz,3,99999,24
output.txt
Name | ID | Salary | Years experience -----+----+--------+----------------- Foo | 1 | 13890 | 12 Bar | 2 | 2342 | 3 Baz | 3 | 99999 | 24
Hi,
Please find the code below .
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.RandomAccessFile;
class Main
{
public static void main(String[] args) throws
FileNotFoundException
{
Scanner scanner = new Scanner(new File("data.csv"));
// we are using scanner class to read the csv file.
scanner.useDelimiter(",");
FileWriter writer = null;
String tobeWrittenToTextFile="";
while(scanner.hasNext())
{
tobeWrittenToTextFile += scanner.next()+"|";
// Everything read from file is appended to a string.which is used
later to output to a text file.
}
System.out.println(tobeWrittenToTextFile);
//Till here we have read the input csv file.
scanner.close();
// 2.Now lets open a file called output.txt and write to it the
read string.
try
{
writer = new FileWriter("output.txt");
writer.write(tobeWrittenToTextFile);
writer.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
output and input files attached:(If you dont need line after column headings you can remove that)
output.txt:
Thanks,
kindly upvote.