我们可以在 CSV 中添加一个新列作为最后一列吗?假设该列已经有 3 列,其中包含一些数据?因此,这个新列稍后将作为第四列添加,而且每一行都应该有随机数。
示例,
Id Name Address Calculated
1 John U.K. 341679
2 Vj Aus 467123
3 Scott U.S. 844257
据我了解,这需要首先读取 csv,for 循环可能是迭代到最后一列,然后添加一个新的计算列,即写入 csv。而添加值的可能是Java的Random类。但究竟如何才能做到这一点才是真正的问题。像示例代码会很有帮助。
代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
String[] csvData = line.split(cvsSplitBy);
int arrayLength = csvData.length;
}
}
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
}
}
最佳答案
太好了,根据您提供的代码,这可能如下所示
(只是为了给你一个想法 - 我在没有测试的情况下即时写在这里......) :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Demo1 {
//moved your random generator here
public static String getRandomNumber() {
/* Code to generate random number */
String CHARS = "1234567890";
StringBuilder random = new StringBuilder();
Random rnd = new Random();
while (random.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * CHARS.length());
random.append(CHARS.charAt(index));
}
String finaldata = random.toString();
return finaldata;
}
public static void main(String[] args) throws IOException {
String csvFile = "C:\\MyData\\Input.csv";
String temporaryCsvFile = "C:\\MyData\\Output_temp.csv";
String line = "";
String cvsSplitBy = ",";
String newColumn = "";
List<String> aobj = new ArrayList<String>();
/* Code to read Csv file and split */
BufferedWriter writer = new BufferedWriter(new FileWriter(
temporaryCsvFile));
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null)
{
//String[] csvData = line.split(cvsSplitBy);
//int arrayLength = csvData.length;
//actually you don't even need to split anything
String newFileLine = line + cvsSplitBy + getRandomNumber();
// ... We call newLine to insert a newline character.
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
//Now delete the old file and rename the new file
//I'll leave this to you
}
}
关于java - 如何向 CSV 添加包含 Java 数据的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52897448/