проблема с разделителем при чтении из CSV в SQLite - PullRequest
0 голосов
/ 27 августа 2018

Я пробовал каждый поиск в сети, но не смог найти решение. Мне удалось создать CSV-файл (как на картинке). Но, импортируя его в sqlite независимо от того, что я делаю, я не могу иметь правильные строки в правильных позициях в моем sqlite, я верю, что речь идет о разделителях, но не могу узнать, можете ли вы мне помочь, пожалуйста, я ищу это для последние 2 дня. спасибо

File exportDir = new File(Environment.getExternalStorageDirectory(), "/XXX/");
                if (!exportDir.exists()) { exportDir.mkdirs(); }

                File file2 = new File(exportDir, "XXX.csv");
                FileReader file = new FileReader(file2);
                BufferedReader buffer = new BufferedReader(file);
                ContentValues contentValues=new ContentValues();
                String line = "";
                String tableName =WordListOpenHelper.MY_LIST_TABLE; 

                db.beginTransaction();
                while ((line = buffer.readLine()) != null)

                {
                    x++;
                    String[] str = line.split("\\+");  

                   if (x>5) {

                       contentValues.put(Contract.WordList.KEY_ENTRY, str[0]);

                       contentValues.put(Contract.WordList.KEY_NICKNAME_DATE, str[1]);
                      contentValues.put(Contract.WordList.KEY_LOCATION, str[2]);
                       contentValues.put(Contract.WordList.KEY_LOCATION_IMAGE, str[3]);
                       contentValues.put(Contract.WordList.KEY_HEART, str[4]);
                       db.insert(tableName, null, contentValues);
                   }

                }
                db.setTransactionSuccessful();
                db.endTransaction();

И класс CSVWriter

 public class CSVWriter {

private PrintWriter pw;
private String separator;
private char escapechar;
private String lineEnd;
private char quotechar;

public static final String DEFAULT_SEPARATOR = "+\n";
public static final char NO_QUOTE_CHARACTER = '\u0000';
public static final char NO_ESCAPE_CHARACTER = '\u0000';
public static final String DEFAULT_LINE_END = "+\n";
public static final char DEFAULT_QUOTE_CHARACTER = '"';
public static final char DEFAULT_ESCAPE_CHARACTER = ' ';


public CSVWriter(Writer writer) {
    this(writer, DEFAULT_SEPARATOR, DEFAULT_QUOTE_CHARACTER,
            DEFAULT_ESCAPE_CHARACTER, DEFAULT_LINE_END);
}

public CSVWriter(Writer writer, String separator, char quotechar, char escapechar, String lineEnd) {
    this.pw = new PrintWriter(writer);
    this.separator = separator;
    this.quotechar = quotechar;
    this.escapechar = escapechar;
    this.lineEnd = lineEnd;
}

public void writeNext(String[] nextLine) {
    try{

    if (nextLine == null)
        return;

    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < nextLine.length; i++) {

        if (i != 0) {
            sb.append(separator);
        }

        String nextElement = nextLine[i];
        if (nextElement == null)
            continue;
        if (quotechar != NO_QUOTE_CHARACTER)
            sb.append(quotechar);
        for (int j = 0; j < nextElement.length(); j++) {
            char nextChar = nextElement.charAt(j);
            if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
                sb.append(escapechar).append(nextChar);
            } else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
                sb.append(escapechar).append(nextChar);
            } else {
                sb.append(nextChar);
            }
        }
        if (quotechar != NO_QUOTE_CHARACTER)
            sb.append(quotechar);
    }
    sb.append(lineEnd);
    pw.write(sb.toString());
}
    catch (Exception ex) {
        ex.printStackTrace();
    }
}
public void close() throws IOException {
    pw.flush();
    pw.close();
}
public void flush() throws IOException {
    pw.flush();
}
}

Файл CSV в файловом менеджере:

enter image description here

1 Ответ

0 голосов
/ 27 августа 2018

Это не совсем CSV-файл, поэтому он требует специальных действий.
Используйте этот метод:

public String getLine(String line) {
    line = line.trim();
    if (line.isEmpty())
        return "";
    if (line.equals("\"\"+"))
        return "";

    if (line.length() <= 3)
        return "";

    return line.substring(1, line.length() - 1);
}

и это вместо вашего while цикла:

    boolean noMoreLines = false;

    for (int i = 1; i <= 5; i++) {
        line = buffer.readLine();
        if (line == null) {
            noMoreLines = true;
            break;
        }
    }

    if (!noMoreLines) {
        while ((line = buffer.readLine()) != null) {
            contentValues.put(Contract.WordList.KEY_ENTRY, getLine(line));

            if ((line = buffer.readLine()) != null)
                contentValues.put(Contract.WordList.KEY_NICKNAME_DATE, getLine(line));
            if ((line = buffer.readLine()) != null)
                contentValues.put(Contract.WordList.KEY_LOCATION, getLine(line));
            if ((line = buffer.readLine()) != null)
                contentValues.put(Contract.WordList.KEY_LOCATION_IMAGE, getLine(line));
            if ((line = buffer.readLine()) != null)
                contentValues.put(Contract.WordList.KEY_HEART, getLine(line));

            db.insert(tableName, null, contentValues);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...