humble_bee
humble_bee

Reputation: 25

insert data to a csv file using java code in eclipse

I am trying to develop a recommender system using Movielens 100k movies dataset. I t works fine for userid already present in dataset but I want to sign up a new user , get his ratings on a fixed no. of movies(say 5) and then give him recommendations based on analysis. For analysis, I would need to add the ratings he provided(to 5 movies) to my dataset which is in csv form. Check my eclipse maven directory structure from screenshot. I want to modify ratings.csv under data folder.

once i fetch data from front end , how can I append it in ratings.csv so as to expand my dataset and thus allow new users to get recommendations.

enter image description here

ratings.csv contains following columns

  user_id     movie_id    ratings

can I somehow append data to ratings.csv

Upvotes: 0

Views: 848

Answers (1)

Samir
Samir

Reputation: 705

private static void writeToCSV(List<Data> dataList) throws FileNotFoundException {
    PrintWriter pw = new PrintWriter(new File("D:\\test.csv"));
    StringBuilder sb = new StringBuilder();
    sb.append("PAN,");
    sb.append("REASON,");
    sb.append("DATE");
    sb.append("\n");

    dataList.stream().map((data) -> {
        sb.append(data.getPan() + ",");
        return data;
    }).map((data) -> {
        sb.append(data.getReason() + ",");
        return data;
    }).map((data) -> {
        sb.append(data.getDateTime() + "");
        return data;
    }).forEach((_item) -> {
        sb.append("\n");
    });

    pw.write(sb.toString());
    pw.close();
    System.out.println("done!");
}

If you want to format csv data with space then you can use StringUtils (org.apache.commons.lang)

private static String rightPad(String text, int length) {
        return StringUtils.rightPad(text, length, " ");
    }

    private static String leftPad(String text, int length) {
        return StringUtils.leftPad(text, length, " ");
    }

So to write data to csv file i think not need another lib

Upvotes: 1

Related Questions