gpt4 book ai didi

java - 用双引号将 CSV 行引起来/创建自定义 main 方法

转载 作者:行者123 更新时间:2023-11-30 07:16:39 26 4
gpt4 key购买 nike

我必须采用 IBM 创建的 CSVReader 并进行更改以满足我的要求。我是java新手,不知道如何做除了#1之外的任何事情,我的要求是:

  1. 通过命令行获取 CSV
  2. 添加主方法
  3. 每行用双引号引起来
  4. 输出新的 CSV

例如。输入乔丹,迈克尔,J,”,23
前任。输出“乔丹,迈克尔,J,”,23“

背景信息:该程序将被添加到 shell 脚本中,正在添加该功能,因为如果输入单个双引号,则 csv 会损坏

这是代码:

package Scripts;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

public class CSVReader
{
private BufferedReader br;
private boolean hasNext = true;
private static char separator = ' ';
private static char quotechar = ' ';

public static final char DEFAULT_SEPARATOR = ',';
public static final char DEFAULT_QUOTE_CHARACTER = '"';

public static void main(final String[] args) throws IOException {
final String csvFile = args[0];
final ArrayList<String[]> allElements = new ArrayList<String[]>();
final CSVReader csvReader = new CSVReader(br, separator, quotechar, csvFile);
csvTransformer.readAll();
csvTransformer.close();
}

public CSVReader(final Reader reader) throws FileNotFoundException {
this(reader, DEFAULT_SEPARATOR);
}

public CSVReader(final Reader reader, final char separator) throws FileNotFoundException {
this(reader, separator, DEFAULT_QUOTE_CHARACTER, null);
}
public CSVReader(final Reader reader, final char separator, final char quotechar, final String csvFile) throws FileNotFoundException {
CSVTransformer.br = new BufferedReader(new FileReader(csvFile));
this.separator = separator;
this.quotechar = quotechar;
}


/**
* Reads the entire file into a List with each element being a String[] of tokens.
*
* return a List of String[], with each String[] representing a line of the file.
*/
public List readAll() throws IOException
{
List allElements = new ArrayList();
while (hasNext)
{
String[] nextLineAsTokens = readNext();
if (nextLineAsTokens != null)
allElements.add(nextLineAsTokens);
}
return allElements;
}

/**
* Reads the next line from the buffer and converts to a string array.
*
* return a string array with each comma-separated element as a separate entry.
*/
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}

/**
* Reads the next line from the file.
*
* return the next line from the file without trailing newline
*/
private String getNextLine() throws IOException {
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}

/**
* Parses an incoming String and returns an array of elements.
*
* @param nextLine
* the string to parse
* @return the comma-tokenized list of elements, or null if nextLine is null
* @throws IOException if bad things happen during the read
*/
private String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List tokensOnThisLine = new ArrayList();
StringBuffer sb = new StringBuffer();
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
if (nextLine == null)
break;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == quotechar) {
// this gets complex... the quote may end a quoted block, or escape another quote.
// do a 1-char lookahead:
if(inQuotes) // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& nextLine.charAt(i+1) == quotechar )
{ // ..and that char. is a quote also.
// we have two quote chars in a row == one quote char, so consume them both and
// put one on the token. we do *not* exit the quoted text.
sb.append(nextLine.charAt(i+1));
i++;
}
else
{
inQuotes = !inQuotes;
}
}
else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuffer(); // start work on next token
}
else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString());
return (String[]) tokensOnThisLine.toArray(new String[0]);
}

public void close() throws IOException {
br.close();
}
}
on

最佳答案

如果您唯一需要的是转义双引号,一个简单的方法就是不将 CSV 文件视为 CSV,而是将其视为简单的文本文件。

首先:Java 中的 main 方法非常简单。使用此声明:

public static void main(String... args){
//do your stuff
// args is a String array containing parameters passed to your script, like your file. to get the first param, use args[0] , for the second it's args[1] ...
}

如果在被调用的java类中找到main方法,java将自动使用main方法。

重要的一点:main方法必须是公共(public)静态的并且不返回任何内容正如您在这里看到的:Java spec, chapter 12

根据您的需要,读取文件中的每一行并将其替换为新文件中此函数的结果:

/**
*
* replace quotes in a line and append/prepend quotes to the line and return it
*
*/
private static String correctQuotesInLine(String nextLine) {
if (nextLine == null) {
return null;
}

//replace any single " in line
String result = nextLine.replaceAll("\"", "\"\"");
//prepend and append line with quotes
result = "\"" + result + "\"";


return result;
}

要写入结果文件,您可以使用这些信息:

how to write files line by line using java

关于java - 用双引号将 CSV 行引起来/创建自定义 main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38275230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com