[英]How to append text in a csv file at the end of each line Java?
I have a csv file with testdata:我有一个带有 testdata 的 csv 文件:
31-September-2017 01:52:57 02:11:25
31-September-2017 01:52:57 02:11:25
I want to write the test result(PASS/FAIL) for every line of data at the end of each line, like this:我想在每一行的末尾为每一行数据写测试结果(通过/失败),如下所示:
31-September-2017 01:52:57 02:11:25 PASSED
31-September-2017 01:52:57 02:11:25 FAILED
I am using openCSV api to read the file content.我正在使用 openCSV api 来读取文件内容。 When I open the same file using CSVWriter, it is deleting all the contents of the file.当我使用 CSVWriter 打开同一个文件时,它会删除文件的所有内容。 Used BufferedWriter as well, same problem.也用过 BufferedWriter,同样的问题。
Please suggest me how I can achieve this with the original contents of file remaining same, and appending the test result at the end of each line.请建议我如何在文件的原始内容保持不变的情况下实现这一点,并在每行的末尾附加测试结果。 Thanks.谢谢。
Use BufferedReader
and BufferedWriter
for this:为此使用BufferedReader
和BufferedWriter
:
PASSED
/ FAILED
to each line before writing在写入之前将PASSED
/ FAILED
添加到每一行I'll try to explain why this will be the best way:我将尝试解释为什么这将是最好的方法:
O(n)
while n
is the size of the file)它的效率( O(n)
而n
是文件的大小)Something simillar like below should work with opencsv.类似下面的东西应该适用于 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);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.