用java更改csv分隔符

时间:2015-07-21 19:10:17

标签: java csv

当我使用AT_SEPARATOR =","时,代码完全正常。但出于某种原因,我想改变我的AT_SEPARATOR =" @@@"而不是","。因此,当我向csv文件添加数据时,它会在找到" @@@"时将数据插入新单元格。但我不知道如何更改csv文件的格式,以便其默认分隔符从","到" @@@"。我在哪里更改或添加一些内容来更改csv默认分隔符? 这是我在不同类中写入csvfile的方法。 在这里,AT_SEPARATOR =" @@@&#34 ;;

CSVFileWriter csvFileMethod = new CSVFileWriter();
csvFileMethod.createCSV(fileName);
while(rs.next()) {  
    csvFileMethod.saveIt(startTime,
            rs.getString("OWNER") + AT_SEPARATOR + 
            rs.getString("NAME") + AT_SEPARATOR +
            rs.getString("TYPE") + AT_SEPARATOR +
            rs.getInt("LINE") + AT_SEPARATOR +
            rs.getString("TEXT") + AT_SEPARATOR +
            parentSYSTEM_ID + AT_SEPARATOR+
            parentPlatform); 
} 
csvFileMethod.closeCSV();

这是我的CSV编写器类。

public class CSVFileWriter {

    public final String NEW_LINE_SEPARATOR;
    public final String AT_SEPARATOR;
    public String Owner;
    public String Table_Name;
    public String systemID;
    public String platform; 
    FileWriter fileWriter;

    public CSVFileWriter(){
        NEW_LINE_SEPARATOR = "\n";
        fileWriter = null;
        AT_SEPARATOR="@@@"; 
    }

    public void createCSV(String fileName){
        try {
            fileWriter = new FileWriter(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveIt(String startTime, String data){
        try {
            fileWriter.append(data);
            fileWriter.append(AT_SEPARATOR);
            fileWriter.append(startTime); 
            fileWriter.append(NEW_LINE_SEPARATOR);          
        } catch (Exception e) {
            System.out.println("Error in CsvFileWriter !!!");
            e.printStackTrace();
        }
    }

    public void saveIt(String startTime, String data, int numberOfRows){
        try {
            fileWriter.append(data);
            fileWriter.append(AT_SEPARATOR);
            fileWriter.append(startTime); 
            fileWriter.append(AT_SEPARATOR);
            fileWriter.append(numberOfRows+"");
            fileWriter.append(NEW_LINE_SEPARATOR);          
        } catch (Exception e) {
            System.out.println("Error in CsvFileWriter !!!");
            e.printStackTrace();
        }
    }

    public void closeCSV(){
        try {
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            System.out.println("Error while flushing/closing fileWriter !!!");
            e.printStackTrace();
        }
    }
}

0 个答案:

没有答案