Read specific row in csv - java

Is there any way through which we can read specific row record on the basis of value. For example my csv file is:
ProductID,ProductName,price,availability,type
12345,Anaox,300,yes,medicine
23456,Chekmeter,400,yes,testing
I want to get the row whose ProductID is ‘23456’. i was checking the new CsvReader(“D:\products.csv”).getRawRecord() method, but it doesn’t have any method parameters.

Iterator iterator = CsvReader("D:\\products.csv").Iterator();
while(iterator.hasNext()){
if((String[] string = (iterator.next))[0] == 23456)
sout("Found the row: " + string[0] + ", " + string[1] + ", " + string[2] + ", " + string[3] + ", " + string[4]);
}
And regarding your concern about performance:
with 1.000 elements this will still be way faster than you need it to be, worry when you get to 1.000.000 elements
If you want the reading of the Csv to be performant you gotta use a performant way of storing your IDs. If you are just incrementing your IDs everytime a new one is made and never delete an ID you can use the ID as an index to directly get the correct line.

public static ArrayList<String> getSpecificRowData(String s) throws IOException
{
String csvFile = s;
BufferedReader br = null;
String line = "";
ArrayList<String> arr=new ArrayList<>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
//write your row name in the given csv file
if(line.contains("write your row name"))
{
arr.add(line);
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return arr;
}
//return the row in the form of ArrayList
ArrayList<String> li=getSpecificRowData("FileName12.csv");
System.out.println(li);

Related

Test if strings are equal with Junit returns false even if its egual

I have a method that returns a String and I would like to test if it works correctly. For that I have a test.txt-file that I read and compare to the return value of my method. If I print both Strings out they are exactly the same! Somehow assertEquals still fails.. What am I doing wrong here?
Method to test:
public String statement() {
String result = "Rental Record for " + getName() + "\n";
int frequentRenterPoints = 0;
for (Rental each : this.rentals) {
frequentRenterPoints += each.getFrequentRenterPoints();
// show figures for this rental
result += "\t" + each.getMovie().getTitle() + "\t"
+ " (" + each.getMovie().getQuality() + ")"
+ ": "
+ String.valueOf(each.getCharge()) + "\n";
}
// add footer lines
result += "Amount owed is " + String.valueOf(getTotalCharge()) + "\n";
result += "You earned " + String.valueOf(frequentRenterPoints)
+ " frequent renter points";
return result;
}
Test:
#Test
public void statementReturnsCorrectlyFormattedString() throws IOException {
// given
customer = new Customer("ElonMusk");
Movie movieOne = new Movie("IronMan1", PriceCodes.REGULAR, Quality.HD);
Movie movieTwo = new Movie("AvengersEndGame", PriceCodes.NEW_RELEASE, Quality.FOUR_K);
Rental rentalOne = new Rental();
rentalOne.setMovie(movieOne);
rentalOne.setDaysRented(5);
Rental rentalTwo = new Rental();
rentalTwo.setMovie(movieTwo);
rentalTwo.setDaysRented(1);
List<Rental> rentalList = new LinkedList<Rental>();
rentalList.add(rentalOne);
rentalList.add(rentalTwo);
customer.setRentals(rentalList);
String expectedString = "";
try {
expectedString = readFile("test.txt");
System.out.println("expected: " + "\n" +expectedString);
} catch (IOException e) {
throw new IOException("Error reading statementTestFile!", e);
}
// when
String statement = customer.statement();
// then
System.out.println("statement: " + "\n" + statement);
System.out.println(expectedString.equals(statement));
assertEquals(expectedString, statement);
}
Output: expectedString
expected:
Rental Record for ElonMusk
IronMan1 (HD): 6.5
AvengersEndGame (FOUR_K): 5.0
Amount owed is 11.5
You earned 2 frequent renter points
Output: statement
statement:
Rental Record for ElonMusk
IronMan1 (HD): 6.5
AvengersEndGame (FOUR_K): 5.0
Amount owed is 11.5
You earned 2 frequent renter points
readFile:
private String readFile(String file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = "\n";
try {
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
return stringBuilder.toString();
} finally {
reader.close();
}
}
The problem is in the trailing newline you add when reading from a file. You could in trim the string, but what if there were some empty lines at the end of file you wanted to read?
So you can either introduce a 'first line' boolean like that:
boolean isFirstLine = true;
while((line = reader.readLine()) != null) {
if (!isFirstLine) {
stringBuilder.append(ls);
}
stringBuilder.append(line);
isFirstLine = false;
}
Or maybe leave the loop as-is and after it runs delete last character from the builder with:
if (stringBuilder.length() > 0) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1); // or stringBuilder.lastIndexOf("\n");
}
Or do a substring.
Or maybe read the lines into a List collection like ArrayList and later do String.join("\n", linesCollection);.

while loop needs to continue

I have this code
static String sCurrentLine = null;
/* keyword */
static String keyword = null;
Scanner keywordFile = null, siteFile = null;
try {
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
siteFile = new Scanner(new FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
keyword = keywordFile.nextLine().trim();
while (sCurrentLine != null){
while (keywordFile.hasNext() || keyword == null) {
System.out.println("Line--> " + keyword);
System.out.println("Current here >>" + sCurrentLine);
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
keyword = keywordFile.nextLine();
System.out.println("next keyword " + keyword);
///* reset search to top of site file */
siteFile = new Scanner(new
FileReader(fileChooser.getSelectedFile()));
sCurrentLine = siteFile.nextLine().trim();
}
else {
sCurrentLine = siteFile.nextLine();
if (sCurrentLine == null) {
break;
}
if (!sCurrentLine.matches(keyword)){
System.out.println("The following keyword " + keyword + " does not exist in file "
+ fileChooser.getSelectedFile());
}
}
} //2nd while loop
}
}
catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
siteFile.close();
keywordFile.close();
}
and i have a text file called keywords which has a list of keywords in it,
but my logic is off an I cannot figure out why.
I think I may need to run the loop one last time but not sure how to do that
My issue is that the last word in the keyword file never gets read in. so the program stops at the 2nd to last element in the text file.
I am not sure that I understand what your code should do.
If I understood correctly your code, your task is to read keywords from a file with keywords and then find all keywords in another file. Is it correct?
You should separate reading keywords from the file and search for them in the file. You should 'load' keywords in a list and then search through the file.
To load keywords in list
keywordFile = new Scanner(new File("/home/mearts/keywords.txt"));
List<String> keywordsList = new ArrayList<>();
while (keywordFile.hasNextLine()) {
keywordsList.add(keywordFile.nextLine());
}
And to search for keywords in the file
siteFile = new Scanner((Readable) new FileReader(fileChooser.getSelectedFile()));
while (siteFile.hasNextLine()) {
String sCurrentLine = siteFile.nextLine().trim();
for (String keyword : keywordsList) {
if (sCurrentLine.contains(keyword)) {
System.out.println("Found it-->> " + keyword);
break;
}
}
System.out.println(
"The following keyword " + keyword + " does not exist in file " + fileChooser.getSelectedFile());
}
I hope this will help :)

Assign a unique key to repeated Arraylist items. and Keep track of Ordering in java

I have a data like :
in an arraylist of Strings I am collecting names .
example:
souring.add(some word);
later I have something in souring = {a,b,c,d,d,e,e,e,f}
I want to assign each element a key like:
0=a
1=b
2=c
3=d
3=d
4=e
4=e
4=e
5=f
and then I store all ordering keys in an array . like:
array= [0,1,2,3,3,4,4,4,5]
heres my code on which I am working :
public void parseFile(String path){
String myData="";
try {
BufferedReader br = new BufferedReader(new FileReader(path)); {
int remainingLines = 0;
String stringYouAreLookingFor = "";
for(String line1; (line1 = br.readLine()) != null; ) {
myData = myData + line1;
if (line1.contains("relation ") && line1.endsWith(";")) {
remainingLines = 4;//<Number of Lines you want to read after keyword>;
stringYouAreLookingFor += line1;
String everyThingInsideParentheses = stringYouAreLookingFor.replaceFirst(".*\\((.*?)\\).*", "$1");
String[] splitItems = everyThingInsideParentheses.split("\\s*,\\s*");
String[] sourceNode = new String[10];
String[] destNode = new String[15];
int i=0;
int size = splitItems.length;
int no_of_sd=size;
tv.setText(tv.getText()+"size " + size + "\n"+"\n"+"\n");
sourceNode[0]=splitItems[i];
// here I want to check and assign keys and track order...
souring.add(names);
if(size==2){
destNode[0]=splitItems[i+1];
tv.setText(tv.getText()+"dest node = " + destNode[0] +"\n"+"\n"+"\n");
destination.add(destNode[0]);
}
else{
tv.setText(tv.getText()+"dest node = No destination found"+"\n"+"\n"+"\n");
}
} else if (remainingLines > 0) {
remainingLines--;
stringYouAreLookingFor += line1;
}
}
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
How can I do this?
can any one help me in this..?
I would advise you to use ArrayList instead of String[]
So, if you want to add an element you just write
ArrayList<String> list = new ArrayList<String>;
list.add("whatever you want");
Then, if you want to avoid repetitions just use the following concept:
if(!list.contains(someString)){
list.add(someString);
}
And if you want to reach some element you just type:
list.get(index);
Or you can easily find an index of an element
int index=list.indexOf(someString);
Hope it helps!
Why don't you give it a try, its take time to understand what you actually want.
HashMap<Integer,String> storeValueWithKey=new HashMap<>();
// let x=4 be same key and y="x" be new value you want to insert
if(storeValueWithKey.containsKey(x))
storeValueWithKey.get(x)+=","+y;
else
storeValueWithKey.put(z,y); //Here z is new key
//Than for searching ,let key=4 be value and searchValue="a"
ArrayList<String> searchIn=new ArrayList<>(Arrays.asList(storeValueWithKey.get("key").split(",")));
if(searchIn.contains("searchValue"))
If problem still persist than comment

Java CSVReader ignore commas in double quotes

I have a CSV file that I am having trouble parsing. I am using the opencsv library. Here is what my data looks like and what I am trying to achieve.
RPT_PE,CLASS,RPT_MKT,PROV_CTRCT,CENTER_NM,GK_TY,MBR_NM,MBR_PID
"20150801","NULL","33612","00083249P PCP602","JOE SMITH ARNP","NULL","FRANK, LUCAS E","50004655200"
The issue I am having is the member name ("FRANK, LUCAS E") is being split into two columns and the member name should be one. Again I'm using opencsv and a comma as the separator. Is there any way I can ignore the commas inside the double-quotes?
public void loadCSV(String csvFile, String tableName,
boolean truncateBeforeLoad) throws Exception {
CSVReader csvReader = null;
if (null == this.connection) {
throw new Exception("Not a valid connection.");
}
try {
csvReader = new CSVReader(new FileReader(csvFile), this.seprator);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("Error occured while executing file. "
+ e.getMessage());
}
String[] headerRow = csvReader.readNext();
if (null == headerRow) {
throw new FileNotFoundException(
"No columns defined in given CSV file."
+ "Please check the CSV file format.");
}
String questionmarks = StringUtils.repeat("?,", headerRow.length);
questionmarks = (String) questionmarks.subSequence(0, questionmarks
.length() - 1);
String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
System.out.println("Base Query: " + query);
String headerRowMod = Arrays.toString(headerRow).replaceAll(", ]", "]");
String[] strArray = headerRowMod.split(",");
query = query
.replaceFirst(KEYS_REGEX, StringUtils.join(strArray, ","));
System.out.println("Add Headers: " + query);
query = query.replaceFirst(VALUES_REGEX, questionmarks);
System.out.println("Add questionmarks: " + query);
String[] nextLine;
Connection con = null;
PreparedStatement ps = null;
try {
con = this.connection;
con.setAutoCommit(false);
ps = con.prepareStatement(query);
if (truncateBeforeLoad) {
//delete data from table before loading csv
con.createStatement().execute("DELETE FROM " + tableName);
}
final int batchSize = 1000;
int count = 0;
Date date = null;
while ((nextLine = csvReader.readNext()) != null) {
System.out.println("Next Line: " + Arrays.toString(nextLine));
if (null != nextLine) {
int index = 1;
for (String string : nextLine) {
date = DateUtil.convertToDate(string);
if (null != date) {
ps.setDate(index++, new java.sql.Date(date
.getTime()));
} else {
ps.setString(index++, string);
}
}
ps.addBatch();
}
if (++count % batchSize == 0) {
ps.executeBatch();
}
}
ps.executeBatch(); // insert remaining records
con.commit();
} catch (SQLException | IOException e) {
con.rollback();
e.printStackTrace();
throw new Exception(
"Error occured while loading data from file to database."
+ e.getMessage());
} finally {
if (null != ps) {
ps.close();
}
if (null != con) {
con.close();
}
csvReader.close();
}
}
public char getSeprator() {
return seprator;
}
public void setSeprator(char seprator) {
this.seprator = seprator;
}
public char getQuoteChar() {
return quoteChar;
}
public void setQuoteChar(char quoteChar) {
this.quoteChar = quoteChar;
}
}
Did you try the the following?
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), ',');
I wrote a following program and it works for me, I got the following result:
[20150801] [NULL] [33612] [00083249P PCP602] [JOE SMITH ARNP] [NULL]
[FRANK, LUCAS E] [50004655200]
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CVSTest {
/**
* #param args
*/
public static void main(String[] args) {
CSVReader reader = null;
try {
reader = new CSVReader(new FileReader(
"C:/Work/Dev/Projects/Pure_Test/Test/src/cvs"), ',');
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String[] nextLine;
try {
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println("[" + nextLine[0] + "] [" + nextLine[1]
+ "] [" + nextLine[2] + "] [" + nextLine[3] + "] ["
+ nextLine[4] + "] [" + nextLine[5] + "] ["
+ nextLine[6] + "] [" + nextLine[7] + "]");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
According to the documentation, you can supply custom separator and quote characters in the constructor, which should deal with it:
CSVReader(Reader reader, char separator, char quotechar)
Construct your reader with , as separator and " as quotechar.
It is simple to load your CSV as an SQL table into HSQLDB, then select rows from the table to insert into another database. HSQLDB handles commas inside quotes. You need to define your text source as "quoted". See this:
http://hsqldb.org/doc/2.0/guide/texttables-chapt.html
Your case should be handled out of the box with no special configuration required.
If you can't make it work, then just switch to uniVocity-parsers to do this for you - it's twice as fast in comparison to OpenCSV, requires much less code and is packed with features.
CsvParserSettings settings = new CsvParserSettings(); // you have many configuration options here - check the tutorial.
CsvParser parser = new CsvParser(settings);
List<String[]> allRows = parser.parseAll(new FileReader(new File("C:/Work/Dev/Projects/Pure_Test/Test/src/cvs")));
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

java.util.ConcurrentModificationException Exception error

i am trying to make a java application with GUI.
i am writing a code that i want to let the User change some data and save these changes on a text file. Before doing that i want to delete the old data that is changed from a list and then rewrite the new data with the last change.if i am missing any class you wanted to see please tell me i will put it online as fast as possible
this is my
public void saveChanges(footBall Player, String name, String level,
int[] scores, int footSize) {
try {
if (CompetitorsList.size() != 0) {
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
String Number = Player.playerNumber + "";
if (C.getPlayerNumberAsString().equals(Number)) {
System.out.println("c");
//the error hit me here when i try to remove the object from the list the exception error is java.util.ConcurrentModificationException
CompetitorsList.remove(C);
}
}
}
Name NewName = new Name(name);
System.out.println("Please get in2");
footBall NewPlayer = new footBall(Player.playerNumber, scores,
level, footSize, NewName);
CompetitorsList.add(NewPlayer);
SaveOnFile();
} else {
System.out.println("No List");
}
} catch (Exception ex) {
System.out.print("testing4");
System.out.print("something wrong" + ex);
}
}
this is the SaveOnFile method:
public void SaveOnFile() {
String scoresInString;
FileWriter fw;
try {
fw = new FileWriter("footBall");
for (Competitors C : CompetitorsList) {
if (C instanceof footBall) {
footBall Scores = new footBall();
scoresInString = Scores.returnScoreAsString(C.scores);
fw.write(C.playerNumber + ", " + C.name.getFullName()
+ ", " + C.level + ", " + scoresInString + ","
+ ((footBall) C).footSize() + "\n");
fw.write("\r\n");
}
}
fw.close();
}
// message and stop if file not found
catch (FileNotFoundException fnf) {
System.out.println("File not found ");
System.exit(0);
}
// stack trace here because we don't expect to come here
catch (IOException ioe) {
ioe.printStackTrace();
System.exit(1);
}
}
Calling remove() on a collection invalidates all active iterator. Instead, you have to use the Iterator.remove() method:
for(Iterator<Competitors> it = CompetitorsList.iterator(); it.hasNext(); ) {
Competitors C = it.next();
if(C instanceof ...) {
if(C.getPlayerNumberAsString().equals(Number))
it.remove();
...
This way, the iterator() knows about how the collection changes, which otherwise wouldn't be possible since the ArrayList doesn't track the Iterators it generated.
Alternatively, if you want to use the same "for-next" syntax and not change to the Iterator syntax, collect all the objects to be removed into a temporary collection. e.g.
ArrayList<Competitors> removeThese = new ArrayList<Competitors>();
for (Competitors C : CompetitorsList) {
if (wantToRemove(C)) // your number logic goes here...
removeThese.add(C);
}
CompetitorsList.removeAll(removeThese);

Categories

Resources