使用OpenCSV在Java中编写CSV文件
[编辑]通过编辑我的问题,我解决了问题。我只是通过将以下代码应用于我的方法来解决问题。我决定编辑我的旧问题。因为我解决了问题。
****if (!file.exists())
theRows.clear();****
@Repository
public class DatabaseImpl implements Database {
List<String[]> theRows = new ArrayList<>();
@Override
public int insert(String tableName, List<String> values) {
File file = new File(tableName + ".csv");
if (!file.exists()) {
prepareCsvFileAndInsertDataToCsvFile(values, file);
} else {
prepareCsvFileAndInsertDataToCsvFile(values, file);
}
return 0;
}
private void prepareCsvFileAndInsertDataToCsvFile(List<String> values, File file) {
if (!file.exists())
theRows.clear();
try (CSVWriter writer = new CSVWriter(new FileWriter(file))) {
String[] header = new String[]{"id", "name", "surname", "age", "salary"};
theRows.add(values.toArray(String[]::new));//arasdiracam
writer.writeNext(header);
writer.writeAll(theRows, false);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void update(String tableName, int rowId, List<String> values) {
}
@Override
public List<String> select(String tableName, int rowId) {
return null;
}
}
[Edited] By editing my question, I have solved the problem. I just solved the problem by applying the following code to my method. I came to the decision to edit my old question. Because I have solved the problem.
****if (!file.exists())
theRows.clear();****
@Repository
public class DatabaseImpl implements Database {
List<String[]> theRows = new ArrayList<>();
@Override
public int insert(String tableName, List<String> values) {
File file = new File(tableName + ".csv");
if (!file.exists()) {
prepareCsvFileAndInsertDataToCsvFile(values, file);
} else {
prepareCsvFileAndInsertDataToCsvFile(values, file);
}
return 0;
}
private void prepareCsvFileAndInsertDataToCsvFile(List<String> values, File file) {
if (!file.exists())
theRows.clear();
try (CSVWriter writer = new CSVWriter(new FileWriter(file))) {
String[] header = new String[]{"id", "name", "surname", "age", "salary"};
theRows.add(values.toArray(String[]::new));//arasdiracam
writer.writeNext(header);
writer.writeAll(theRows, false);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void update(String tableName, int rowId, List<String> values) {
}
@Override
public List<String> select(String tableName, int rowId) {
return null;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论