我正在加载CSV文件并保持活动而不关闭BufferReader。现在我想在我的CSV中添加/删除更多行并获取更新的CSV。这意味着我希望在CSV文件被更改时动态通知。
以下是我的示例代码:
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();
}
}
}
}
答案 0 :(得分:1)
CSV处理比你想象的复杂得多。
导致噩梦的问题是不同的列分隔符,语言环境(例如,如果您对列分隔符使用,
,它可能会在某些语言环境中使用双精度值回激,因为它用于表示小数),列有时包裹着特殊字符(如"
或'
),逃避进入图片等。
如果您允许我提供建议,请使用成熟的CSV lib来执行OpenCSV之类的任务(但有很多替代方案)。使用起来非常简单,请参阅链接网站以获取示例。
答案 1 :(得分:0)
使用它。重新构建了代码。如果readLine在返回空值后返回一个数字,则可以假设某些内容已添加到csv文件中。
PS :如果文件内容被删除;代码不起作用。
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();
}
}