Программа Java Добавить двойную кавычку во всей строке - PullRequest
1 голос
/ 08 июля 2019

Я пишу простую программу, которая берет файл CSV и создает CSV с новым столбцом.Моя проблема: программа цитирует старые столбцы и все столбцы.Ниже моего кода

public class CSVmodifier {

    public static void modify(String Path,String Escape) throws IOException {
        int i=0;
        String filename = new File(Path).getName().toString();
        //setName(string) modify the original filename
                String fileoutname = setName(filename);
        File file= new File(fileoutname);
        try {
            FileWriter out = new FileWriter(file);
            Reader reader = 
                        Files.newBufferedReader(Paths.get(Path));
            CSVReader csvReader = new CSVReader(reader);
            CSVWriter csvWriter = new CSVWriter(out);
            String[] nextRecord;
            while ((nextRecord = csvReader.readNext()) != null) {
                int dimension = nextRecord.length;
                String[] newline = new String[dimension+1];
                int y = 0;
                                //formatNumber create a string number with 9 
                                //zero in the front-> 1 > "000000001"
                newline[0]=formatNumber(i+1);
                while(y<dimension) {
                    newline[y+1] = nextRecord[y];
                    y++;
                }
                i+=1;
                csvWriter.writeNext(newline);
            }
            csvWriter.close();


        } finally {


        }
    }

    public static String formatNumber(int i) {
        String formatted = String.format("%09d", i);
        return formatted;
    }


}

мой пример:

"John","Doe","120 jefferson st.","Riverside", "NJ", "08075"

неверный вывод:

"000000001","""John""",""Doe"",""120 jefferson st."",""Riverside"", ""NJ"", ""08075"""

Я не могу загрузить файл, но покажуВы образец файла (входная строка), которые дают ту же проблему:

'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141'; 
'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale elemetare';'Ola!'

Там Выходная строка:

'000000001';"'1231';'02512710795';'+142142';'2019/12/12';'statale';'blablabla';'iradsasad';'-123131';'+414214141'; "
'000000002';"'003';'08206810965';'+000000001492106';'2019/06/23';'Scuola statale'; "

Ответы [ 2 ]

0 голосов
/ 08 июля 2019

Я предполагаю, что ваш CSVWriter класс com.opencsv.CSVWriter.
Вы используете csvWriter.writeNext (String []) , что является сокращением для writeNext(nextLine, true); ( JavaDoc ).
Второй параметр, который в этом случае всегда имеет значение true, равен applyQuotesToAll:

Истина, если все значения должны быть заключены в кавычки.False применяет кавычки только к значениям, которые содержат символы разделителя, экранирования, кавычки или новой строки.

Поэтому все, что вам нужно сделать, это изменить эту строку:

csvWriter.writeNext(newline)

на это:

csvWriter.writeNext(newline, false);
0 голосов
/ 08 июля 2019

Это работает для меня, проверьте и дайте мне знать.Просто измените логику в то время как блок заменяет несколько двойных кавычек на одну кавычку.

public class CSVmodifier {

public static void modify(String Path, String Escape) throws IOException {
    int i = 0;
    String filename = new File(Path).getName().toString();
    //setName(string) modify the original filename
    String fileoutname = setName(filename);
    File file = new File(fileoutname);
    try {
        FileWriter out = new FileWriter(file);
        Reader reader
                = Files.newBufferedReader(Paths.get(Path));
        CSVReader csvReader = new CSVReader(reader);
        CSVWriter csvWriter = new CSVWriter(out);
        String[] nextRecord;
        while ((nextRecord = csvReader.readNext()) != null) {
            int dimension = nextRecord.length;
            String[] newline = new String[dimension + 1];

            int y = 0;
            //formatNumber create a string number with 9 
            //zero in the front-> 1 > "000000001"
            newline[0] = formatNumber(i + 1);
            while (y < dimension) {
                newline[y + 1] = nextRecord[y].replace("\"\"", "\"");
                if (newline[y + 1].startsWith("\"") && newline[y + 1].endsWith("\"")) {
                    newline[y + 1] = newline[y + 1].substring(1, newline[y + 1].length() - 1);
                }
                y++;
            }
            i += 1;
            csvWriter.writeNext(newline);
        }
        csvWriter.close();

    } finally {

    }
}

public static String formatNumber(int i) {
    String formatted = String.format("%09d", i);
    return formatted;
}


}
...