Reputation: 307
I am loading a CSV file and kept alive without closing BufferReader. Now I want to add/delete few more rows to my CSV and get updated CSV. Which means I want dynamically notified when CSV file is altered.
Here is my sample code:
public class Check {
public static void main(String args[]) throws IOException, InterruptedException{
Check ch = new Check();
//args[0] = "C:\\Users\\raponnam\\Desktop\\GxDefault.csv";
String csvFile="C:\\Users\\raponnam\\Desktop\\GxDefault.csv";
int lineCounter=0;
if (csvFile!=null)
{
BufferedReader csvToRead = null;
try{
csvToRead = new BufferedReader(new FileReader(csvFile));
String line;
while ((line=csvToRead.readLine())!=null)
{
lineCounter++;
String[] splitLine = line.split(",");
System.out.println("no of lines-->> "+lineCounter);
}
while(true)
{
System.out.println("wait 6 seconds");
Thread.sleep(6000);
}
}finally{
//csvToRead.close();
}
}
}
}
Upvotes: 0
Views: 999
Reputation: 10606
CSV handling is far more complicated than you would first think.
The issues causing the nightmares are the different column separators, locales (e.g., if you use ,
for column separators it might fire back with doubles on some locales, since it is used to denote the decimals), columns are sometimes wrapped with special characters (like "
or '
), escaping comes into the picture, etc.
If you allow me to have an advice, use a mature CSV lib for the task like OpenCSV (but there are tons of alternatives there). It's quite trivial to use, see the linked site for examples.
Upvotes: 1
Reputation: 1622
Use this. Have restructured your code. If readLine returns a number after returning nulls, you can assume that something has been added to the csv file.
PS: If file contents are deleted; the code doesnt work.
String csvFile = "C:\\a.csv";
int lineCounter = 0;
if (csvFile != null) {
BufferedReader csvToRead = null;
try {
csvToRead = new BufferedReader(new FileReader(csvFile));
String line;
while (true) {
if ((line = csvToRead.readLine()) != null) {
lineCounter++;
String[] splitLine = line.split(",");
System.out.println("no of lines-->> " + lineCounter);
}
System.out.println("wait 6 seconds");
Thread.sleep(6000);
}
} finally {
// csvToRead.close();
}
}
Upvotes: 0