写入CSV文件并进行修改

时间:2015-02-24 14:54:23

标签: java file csv filestream opencsv

我正在使用一个大型数据集的大型csv文件,大约有17个属性和大约40000行。我想以相反的顺序写出每行值的第i个位置(第一行ith“,”分隔值替换为40000 ith“,”分开...第二个替换为39999 ...同样全部)(这里我提取了第12个值) = ith)。我可以这样做请帮助我。!!

package demo;
 import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.FileWriter;
import java.io.*;
/**
 *
/**
 *
 * @author admin
 */
public class Demo {

    /**
     * @param args the command line arguments
     */
      public static void main(String[] args)throws IOException {
        String filename = "bank-full.csv";
        File file = new File(filename);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter("bank-full_updated.csv"));
       } 
   catch (IOException e) {
        } 

        try {
            Scanner inputStream = new Scanner(file);
            inputStream.next();
            double Tuple;
            int count=0;
            Tuple = 0; 


     while (inputStream.hasNext()) 
     {
            String data = inputStream.next();         
            String[] values = data.split(";");
            double balance = Double.parseDouble(values[11]);  
            //balance=balance+1;
             values[11] = String.valueOf(balance);   
    count=count+1;

            // iterate through the values and build a string out of them
            StringBuilder sb = new StringBuilder();
            //  String newData = sb.toString();
            for (int i = 0; i < values.length; i++) {
                    sb.append(values[i]);
                    if (i < values.length - 1) {
                        sb.append(";");
                    }
             }
            // get the new string
            System.out.println(sb.toString());
            writer.write(sb.toString()+"\n");
                }
            writer.close();
            inputStream.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

不确定您为什么要这样做,但听起来您需要将文件读入Collection(例如ArrayList),将每行添加为记录,然后从末尾循环遍历列表开始 - 并将所有内容打印回(新)文件......

相关问题