Java store specific csv value to list - java

The CSV look like this:
Name;Amount;Date
Netflix;5;1.1.2021
I want a different list for each expense, one for entertainment one for transport etc. However, I only want the amount to be stored on a list, how would I do that?
public class CsvReader {
public static void readDataLineByLine(String file) {
try {
// Create an object of file reader class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
// Read all data at once
List<String[]> allData = csvReader.readAll();
List<String> entertainment = new ArrayList<>();
// Print Data.
for (String[] row : allData) {
for (String cell : row) {
System.out.print(cell + "\t");
if (cell.startsWith("Netflix")){
entertainment.add(cell);
}
}
System.out.println();
System.out.println(entertainment);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CsvReader.readDataLineByLine("tt.csv");
}
}

If you use opencsv , how about writing the code like below? Please review.
public class CsvReader {
public static void readDataLineByLine(String file) {
try {
// Create an object of file reader class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvParser object with
// custom separator semi-colon
CSVParser parser = new CSVParserBuilder().withSeparator(';').build();
// create csvReader object with parameter
// filereader and parser
CSVReader csvReader = new CSVReaderBuilder(filereader).withCSVParser(parser).build();
List<String> entertainment = new ArrayList<>();
// changed part
int index = 0;
while ((nextLine = reader.readNext()) != null) { // 2
// csv header exclusion condition
if(index == 0) {
continue;
}
String name = nextLine[0];
String amount = nextLine[1];
if (name.startsWith("Netflix")){
entertainment.add(amount);
}
index++;
}
// Print Data.
System.out.println();
System.out.println(entertainment);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
CsvReader.readDataLineByLine("tt.csv");
}
}

Related

Add Fileinput to Treemap

I can't add the file input to my map. It says I am missing something and that the Items []is not instantiated. I can't seem to figure it out
public class BigCities {
private Map<String, Set<CityItem>> countryMap;
private File file;
public BigCities(String fileName) {
countryMap = new TreeMap<>();
file = new File(fileName);
readFile(fileName);
}
private void readFile(String fileName) {
// Opg 3c implementeres her.
CityItem cityItem;
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
String[] items;
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line.split(";");
line = br.readLine();
cityItem = new CityItem(items[1], items[2], items[3]);
}
String everything = sb.toString();
System.out.println(everything);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String toString() {
return countryMap.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
//Vaelg ANSI eller UTF8 afhaengig af hvad der virker bedst paa din computer:
BigCities bc = new BigCities("EuroCities ANSI.txt");
//BigCities bc = new BigCities("EuroCities UTF8.txt");
System.out.println(bc);
}
}
I Don't know what I am missing to add the input, but hopefully someone has some input.
I Am new to programming and therefore I find it confusing, since I feel like I am following all the right methods.
You never initialize the items array, so when trying to access it, you're getting null, or it may just be caught by the compiler and will give you an error there.
I suspect that you mean to assign the split to items, so change the line
line.split(";");
to
items = line.split(";");

mp3 file path not playing from ArrayList? FileNotFoundException in Java

I am trying to create an MP3 player (console only at the moment) in Java. I have stored a list on track details (Name, Artist, Length, Genre, Pathway to the track e.g. "/Users/harvhead/Desktop/music.txt") in a text file and have used a method access() in my PlayMusic class to put all track details into separate ArrayLists. I have then inherited this Class into a RockMusic class and created a method to find any Rock music (genre) and then place the track pathway into a FileInputStream to then play the Rock Mp3.The problem is that even though the pathway is being passed correctly I am getting a FileNotFoundException (No such File or Directory). What am I doing wrong.????..please help..my code is below....I have spent hours banging my head against a wall trying to figure this out.
public class PlayMusic {
List<String> trackName = new ArrayList<String>();
List<String> artist = new ArrayList<String>();
List<String> length = new ArrayList<String>();
List<String> genre = new ArrayList<String>();
List<String> ID = new ArrayList<String>();
List<String> IDtrack = new ArrayList<String>();
List<String> trackPath = new ArrayList<String>();
File f = new File("/Users/harvhead/Desktop/music.txt");
File t = new File("/Users/harvhead/Desktop/musicTracks.txt");
public void access() throws FileNotFoundException {
Scanner sc = new Scanner(f);
try {
// reading each line of text and placing the 1st 2nd 3rd 4th element into different String Arraylist
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] details = line.split(",");
String trackN = details[0];
String artistN = details[1];
String trackLength = details[2];
String genreN = details[3];
String IDN = details[4];
String Pathtrack = details[5];
trackName.add(trackN);
artist.add(artistN);
length.add(trackLength);
genre.add(genreN);
ID.add(IDN);
trackPath.add(Pathtrack);
}
} catch (Exception e) {
System.out.println("Playlist Error");
}
if (trackName.isEmpty()) {
System.out.println("Arraylist is Empty");
} else {
System.out.println("ArrayList is not Empty");
}
}
Below is the method from my RockMusic Class:
public void rockPlayMusic() throws FileNotFoundException {
// call the access method (from PlayMusic Class) to create arraylists from txt file
access();
// finding Rock tracks and then trying to play them
for (int x = 0; x < genre.size(); x++) {
if (genre.get(x).contains("Rock")) {
try {
FileInputStream fis = new FileInputStream(trackPath.get(x));
System.out.println(trackPath.get(x));
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
Below is my main:
package musicapp;
import java.io.FileNotFoundException;
public class MusicApp {
public static void main(String[] args) throws FileNotFoundException {
rockMusic rock = new rockMusic();
rock.rockPlayMusic();
}
}
Below is my error in the console:
ArrayList is not Empty
java.io.FileNotFoundException: "/Users/harvhead/Desktop/San Tropez.mp3" (No such file or directory)
java.io.FileNotFoundException: "/Users/harvhead/Desktop/Slave To The Wage.mp3" (No such file or directory)
java.io.FileNotFoundException: "/Users/harvhead/Desktop/Six Shooter.mp3" (No such file or directory)
java.io.FileNotFoundException: "/Users/harvhead/Desktop/Bones.mp3" (No such file or directory)
BUILD SUCCESSFUL (total time: 0 seconds)
This is the code for passing the file path manually into the FileInputStream and it plays the mp3 (I also got it to print the file path in the console).
public void manualPlayTest(){
try {
FileInputStream fis = new FileInputStream("/Users/harvhead/Desktop/San Tropez.mp3");
System.out.println("/Users/harvhead/Desktop/San Tropez.mp3");
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
Hardcoded path into rockPlayMusic method and this works fine.
public void rockPlayMusic() throws FileNotFoundException {
// call the access method (from PlayMusic Class) to create arraylists from txt file
access();
// finding Rock tracks and then trying to play them
for (int x = 0; x < genre.size(); x++) {
if (genre.get(x).contains("Rock")) {
try {
FileInputStream fis = new FileInputStream("/Users/harvhead/Desktop/San Tropez.mp3");
System.out.println(trackPath.get(x));
Player playMP3 = new Player(fis);
playMP3.play();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
console output from hardcoded path in rockMusicPLay() method

Sentiment Analysis with OpenNLP on a text file

I have 100 sentences of test data. I am trying to run sentiment analysis on them but no matter what input String I am using, I am only getting a positive estimation of the input string. Each sentence gets a return value of 1.0. Any idea why this might be happening? Even if I use negative example inputs from the .txt file, the result is a positive value.
public class StartSentiment
{
public static DoccatModel model = null;
public static String[] analyzedTexts = {"Good win"};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("src\\sentiment\\Results.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "1");
tp.put(TrainingParameters.ITERATIONS_PARAM, "100");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text) throws IOException{
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(text.split(" ") );
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}

CSVReader does not check the whole file

I am trying to open a csv file using openCSV, iterate over every column and if the userID is different write a new JavaBean pair at the end of the file.
The problem is that the reader only checks the first column of my file and not the whole file. While created, the file contains only a header and nothing else. The program will check every column and if the sudoID is different it will write it to the file. If the sudoID in the first line is equal to the the one imported from my main class it will recognise it and not write it. But if this -same- sudoID is in the second row it will not recognise it and will write it again.
For instance, if my CSV looks like this it will work:
"Patient_id Pseudo_ID",
"32415","PAT106663926"
If it looks like this it will re-write the sudoID:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
Thanks!
My Code:
public class CSVConnection {
#SuppressWarnings({ "deprecation", "resource", "rawtypes", "unchecked" })
public String getID(String sID,String pseudoID) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
try {
CsvToBean csv = new CsvToBean();
String csvFilename = "CsvFile.csv";
Writer writer= new FileWriter(csvFilename,true);
CSVReader csvReader = new CSVReader(new FileReader(csvFilename),',','"',1);
ColumnPositionMappingStrategy strategy = new ColumnPositionMappingStrategy();
strategy.setType(PatientCSV.class);
String[] columns = new String[] {"patID","pseudoID"};
strategy.setColumnMapping(columns);
//Set column mapping strategy
StatefulBeanToCsv<PatientCSV> bc = new StatefulBeanToCsvBuilder<PatientCSV>(writer).withMappingStrategy(strategy).build();
List patList = csv.parse(strategy, csvReader);
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String [] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException{
CSVConnection obj = new CSVConnection();
String sID="32415";
String pseudoID="PAT101830150";
obj.getID(sID,pseudoID);
}
}
and the Java Bean :
public class PatientCSV {
private String patID;
private String pseudoID;
public String getPatID() {
return patID;
}
public void setPatID(String patID) {
this.patID = patID;
}
public String getPseudoID() {
return pseudoID;
}
public void setPseudoID(String pseudoID) {
this.pseudoID = pseudoID;
}
public PatientCSV(String patID, String pseudoID) {
super();
this.patID = patID;
this.pseudoID = pseudoID;
}
public PatientCSV() {
super();
// TODO Auto-generated constructor stub
}
public String toString()
{
return "Patient [id=" + patID + ", pseudoID=" + pseudoID + "]";
}
}
Lets inspect your for loop
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
return pat.getPseudoID();
}
else
{
PatientCSV pat1 = new PatientCSV();
pat1.setPatID(sID);
pat1.setPseudoID(pseudoID);
patList.add(pat1);
/*Find a way to import it to the CSV*/
bc.write(pat1);
writer.close();
return pseudoID;
}
}
So in the case you mention it is not working as expected, meaning that the line that matches your input is the second line:
"Patient_id Pseudo_ID",
"32416","PAT104958880"
"32415","PAT106663926"
So you call: getID("32415", "PAT106663926")
What happens in your loop is:
You take the first element of your csv patients, the one with id: 32416,
check if it matches with the id given as input to your method, 32415.
It does not match so it goes to the else part. There it creates the new patient (with the same patID and pseudoID as the 2nd row of your csv) and stores it in the file.
So by now you should have 2 entries in your csv with the same data "32415","PAT106663926".
I think that this is the error, in your for loop you should check against all entries if there is a match, and then create the patient and store it to the csv.
An example:
PatientCSV foundPatient = null;
for (Object patObj : patList) {
PatientCSV pat = (PatientCSV) patObj;
if(((PatientCSV) patObj).getPatID().equals(sID)){
foundPatient = pat;
}
}
if (foundPatient == null) {
foundPatient = new PatientCSV();
foundPatient.setPatID(sID);
foundPatient.setPseudoID(pseudoID);
patList.add(foundPatient);
/*Find a way to import it to the CSV*/
bc.write(foundPatient);
writer.close();
}
return foundPatient.getPseudoID();
P.S. The above example is written very quickly, just to give you the idea what needs to be done.

Returning an arraylist to be accessed from another class

I'm new to Stackoverflow, so here goes.
I'm currently working on an assignment that requires to read from a csv file and place it into some sort of data collection.
I've gone with an arraylist. But what I seem to be stuck with is that I'm attempting to use my ReadWriteFile class to read the csv file into an arraylist (which works). But I need to somehow access that array in my GUI class to fill my JTable with said data.
After looking through similar help requests, I haven't been able to find any success.
My current code from my ReadWriteFile class;
public static void Read() throws IOException {
String lines = "";
String unparsedFile = "";
String dataArray[];
String col[] = { "COUNTRY", "MILITARY", "CIVILIAN", "POWER" };
FileReader fr = new FileReader("C:/Users/Corbin/Desktop/IN610 - Assignment 1/Programming3_WWII_Deaths.csv");
BufferedReader br = new BufferedReader(fr);
while ((lines = br.readLine()) != null) {
unparsedFile = unparsedFile + lines;
}
br.close();
dataArray = unparsedFile.split(",");
for (String item : dataArray) {
System.out.println(item);
}
ArrayList<String> myArrayList = new ArrayList<String>();
for (int i = 0; i < dataArray.length; i++) {
myArrayList.add(dataArray[i]);
}
}
So what my question is; How can I create a method that returns the values from the array, so I can access that array in my GUI class and add each element to my JTable?
Thanks!
Here is some simple example of how to return array in the method and how to use it in GUI class:
public class Main {
public String[] readFromFile (String filePath) {
ArrayList<String> yourList = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
// read file content to yourList
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return yourList.toArray(new String[yourList.size()]);
}
}
And the GUI class:
public class GUI extends JFrame {
private JTable jTable;
public GUI() {
jTable = new JTable(10, 10);
this.getContentPane().add(jTable);
this.setVisible(true);
this.pack();
}
public void passArrayToTable(Main mainClass) {
String[] array = mainClass.readFromFile("C:\\file.csv");
// for (String s : array) {
// add values to jTable with: jTable.setValueAt(s,row,column);
// }
}
public static void main(String[] args) {
new GUI().passArrayToTable(new Main());
}
}

Categories