【问题标题】:Invalid outout when writing to file with java使用java写入文件时输出无效
【发布时间】:2015-04-02 23:04:01
【问题描述】:

我正在尝试将输出写入 csv 文件,但第一个值采用这种格式

我使用了 ObjectOutputStream。通常第一个值应该是 1,1,1,2,2,2,3.... 这是我的代码有什么想法吗?

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.List;

import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.similarity.ItemSimilarity;

public class ItemRecommend {

    public static void main(String[] args) throws IOException {
        FileOutputStream fos = new FileOutputStream("data/test.csv");
        ObjectOutputStream oos = new ObjectOutputStream(fos);   
        try {
            DataModel dm = new FileDataModel(new File("data/rated.csv"));
            ItemSimilarity sim = new LogLikelihoodSimilarity(dm);
            GenericItemBasedRecommender recommender = new GenericItemBasedRecommender(dm, sim);

                for (LongPrimitiveIterator items = dm.getItemIDs(); items.hasNext();){
                    long itemID = (int)(long) items.nextLong();
                    List<RecommendedItem>recommendations = recommender.mostSimilarItems(itemID, 3);
                for(RecommendedItem recommendation : recommendations){
                    oos.writeObject(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue()+"\n");
                    //System.out.println(itemID + "," + recommendation.getItemID() + "," + recommendation.getValue());                  
                }               
            }   
        } catch (IOException e) {
            System.out.println("Error !");
            e.printStackTrace();
        } catch (TasteException e) {
            System.out.println("Taste exception !");
            e.printStackTrace();
        }
        finally {
            oos.flush();
            oos.close(); 
            }
    }
}

【问题讨论】:

  • 你使用ObjectOutputStream,最初是为序列化POJO而设计的,用来写文本;你用它写一个long。现在,您是否真的希望将生成的文件解码为文本?
  • 那张截图是什么?我在看什么?如果可能,请将其发布为文本。
  • 屏幕截图是文件中的输出 3 逗号分隔值。我对第一价值有疑问,@fge 我正在寻求帮助而不是批评。谢谢
  • 那不是批评家;那是一个提示。您尝试编写一个 text 文件。现在,查看ObjectOutputStream 的javadoc。这真的是你想要的吗?

标签: java io mahout mahout-recommender


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-21
  • 2012-08-26
  • 1970-01-01
相关资源
最近更新 更多