如何在Java中消除选项卡式列csv文件
我需要删除单词“Close”,它用java在第一行末尾的tab分隔。文件的其余部分应保持不变。 我该怎么做 我正在尝试修改此代码:如何在Java中消除选项卡式列csv文件,java,csv,Java,Csv,我需要删除单词“Close”,它用java在第一行末尾的tab分隔。文件的其余部分应保持不变。 我该怎么做 我正在尝试修改此代码: public class removezero{ public static void main(String[] args) throws Exception { //scanner to read csv file Scanner replace = new Scanner(new File("csvfile"));
public class removezero{
public static void main(String[] args) throws Exception {
//scanner to read csv file
Scanner replace = new Scanner(new File("csvfile"));
//array of string
String [][] all= new String [10][10];
//new csv file to write answer
FileWriter removezero = new FileWriter(createReplacedCsv());
int i=0;
StringBuilder builder = new StringBuilder();
//write csv to array
while (replace.hasNext()) {
String[] result = replace.nextLine().split(",");
all[i]= result;
i++;
}
// write from array to builder
for(int j=0;j<5; j++){
for(int k=0;k<5; k++)
if(!(all[1][k]).equals("0")){builder.append(all[j][k]).append(",");}
builder.deleteCharAt(builder.lastIndexOf(","));
builder.append("\n");
}
//write to csv file
removezero.write(builder.toString());
removezero.flush();
removezero.close();
}
private static File createReplacedCsv() throws Exception {
File replacedCsv = new File("removedzero.csv");
replacedCsv.createNewFile();
return replacedCsv;
}
}
公共类removezero{
公共静态void main(字符串[]args)引发异常{
//扫描仪读取csv文件
扫描仪替换=新扫描仪(新文件(“csvfile”);
//字符串数组
字符串[][]all=新字符串[10][10];
//要写入答案的新csv文件
FileWriter removezero=新的FileWriter(createReplacedCsv());
int i=0;
StringBuilder=新的StringBuilder();
//将csv写入阵列
while(replace.hasNext()){
字符串[]结果=replace.nextLine().split(“,”);
全部[i]=结果;
i++;
}
//从数组写入生成器
对于(int j=0;j,假设您定义:
private static String removeTabbedColumn(String line) {
int indexOfTab = line.indexOf('\t');
if (indexOfTab == -1) {
return line;
} else {
return line.substring(0, indexOfTab);
}
}
现在你可以使用
String[] result = removeTabbedColumn(replace.nextLine()).split(",");
我还没有测试过。比如,你为什么不使用CsvParser
final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
try {
for (final CSVRecord record : parser) {
final String string = record.get("SomeColumn");
// Get the intended columns here.
}