我有一个带有testdata的csv文件:
31-September-2017 01:52:57 02:11:25
31-September-2017 01:52:57 02:11:25
我想为每行末尾的每一行数据编写测试结果(PASS / FAIL),如下所示:
31-September-2017 01:52:57 02:11:25 PASSED
31-September-2017 01:52:57 02:11:25 FAILED
我使用openCSV api来读取文件内容。当我使用CSVWriter打开同一个文件时,它将删除该文件的所有内容。使用BufferedWriter也是同样的问题。
请建议我如何实现这一点,文件的原始内容保持不变,并将测试结果附加到每行的末尾。感谢。
答案 0 :(得分:0)
使用BufferedReader
和BufferedWriter
:
PASSED
/ FAILED
添加到每一行
我会尝试解释为什么这是最好的方式:
O(n)
而n
是文件的大小)答案 1 :(得分:0)
类似下面的东西应该与opencsv一起使用。
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Example {
public static void main(String[] args) {
try {
String fileName = "C:\\Users\\eritrean\\Desktop\\yourfile.csv";
List<String[]> myEntries = readFile(fileName);
List<String[]> testedEntries = new ArrayList<>();
for(String[] row : myEntries){
String[] withTestResult = addTestResult(row,randomResult());
testedEntries.add(withTestResult);
}
writeToFile(fileName,testedEntries);
} catch (IOException ex) {
}
}
public static List<String[]> readFile(String fileName) throws IOException {
CSVReader reader = new CSVReader(new FileReader(fileName),'\t','\"',0);
List<String[]> myEntries = reader.readAll();
return myEntries;
}
public static String[] addTestResult(String[] row, String result){
return (String.join("\t", row)+"\t"+result).split("\t");
}
public static String randomResult(){
Random rand = new Random();
return rand.nextBoolean()?"PASSED":"FAILED";
}
public static void writeToFile(String fileName, List<String[]> myEntries) throws IOException {
try (CSVWriter writer = new CSVWriter(new FileWriter(fileName), '\t',CSVWriter.NO_QUOTE_CHARACTER)) {
for(String[] row: myEntries){
writer.writeNext(row);
}
}
}
}