delete item from .csv file using JAVA

问题: enter image description here Hello,I want to delete a row from .csv file using JAVA. that the user can decide witch row they want to delete. The input be like: delete...

问题:

enter image description here

Hello,I want to delete a row from .csv file using JAVA.

that the user can decide witch row they want to delete. The input be like:

delete a number:

A02,40

And the file will be like:

enter image description here

Could anyone give me some suggestion?

This is how I write into .csv file Hope it will help

package finaltest;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class AddCourse {   
public static void main(String[] args) throws Exception {
    Map<String, List<String>> map = new TreeMap<String, List<String>>();
    
BufferedReader reader = new BufferedReader(new FileReader("DB_ID.csv"));
String line = reader.readLine();//read header
while ((line = reader.readLine()) != null) {
    String key = getField(line);
    List<String> l = map.get(key);
    if (l == null) {
        l = new LinkedList<String>();
        map.put(key, l);
    }
    l.add(line);
}
reader.close();

FileWriter additem = new FileWriter("add_ID.csv");
additem.write("item_id, item_prisen");
System.out.println("please input number: ");
Scanner in = new Scanner(System.in);
List<String> input = new LinkedList<String>();
input.add(in.next());

for (String val : input) {
    additem.write(val);
    additem.write("n");
}
in.close();

for (List<String> list : map.values()) {
    for (String val : list) {
        additem.write(val);
        additem.write("n");
    }   
}
additem.close();
}
private static String getField(String line) {
    return line.split(",")[0];// extract value you want to sort on
}
}

回答1:

You read from one file and write to another. Omit the rows not meeting your requirement. When done, delete the original file, rename the new file.

I suggest using a library to help with the chore of reading and writing the CSV. You have a choice a several in the Java ecosystem. My favorite is Apache Commons CSV.

If you are doing this delete operation frequently, you might consider using a database instead.


回答2:

Once you have your CSV data read into lets say a 2-D Array, you can just search the first element of each Array and see if it contains "A02" and then just rewrite the data but dis-include that row.

  • 发表于 2020-06-27 21:51
  • 阅读 ( 160 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除