我正在合作一个项目,目前我已经构建了一个程序,以字符串格式将数据写入 CSV 文件。我的项目合作伙伴说,他认为如果以整数格式编写该产品会更有用,而我一直认为我们的可视化功能可以在读取 CSV 数据时简单地运行 parseInt。
我想在这里问这个问题,以获取一些有关通过使用原始数据类型而不是字符串写入文件可以获得什么的信息。 Java 似乎确实是为了将数据作为字符串写入 CSV 而构建的,但他声称将数据作为 int 写入会更有效。想法?
这实际上更多是一个概念性问题,但我将包含用于生成数据表的代码,以防上下文相关。
//Snippet only
private void elementLocator() {
//Declare ArrayList to hold values
data = new ArrayList<ArrayList<String>>();
//Build data table
try {
//Unique xpath string
String prefix = "//*[@id=\"main_table_countries_today\"]/tbody[1]/tr[";
int j = 2;
System.out.println("Retrieving data...");
for(int i = 1; i <= 222; i ++) {
try {
//Initialize array to fill in to data row by row
ArrayList<String> parser = new ArrayList<String>();
for(j = 2; j <= 13; j ++) {
parser.add(driver.findElement(By.xpath(prefix + i + "]/td[" + j + "]")).getText());
}
//Use a boolean indicator to skip any row that has a blank 1st column
String w = parser.get(0);
boolean v = w.isEmpty();
if(v) {
continue;
}
else {
data.add(parser);
}
//Catch errors
} catch (Exception e) {
e.printStackTrace();;
continue;
}
}
}
public void makeCSV() throws IOException {
//Create output file only if it does not already exist
EST est = new EST();
//Pull year, month, day for file name
String dt = est.getDate();
f = new File(home + "\\Climate Dev Pegasus\\Data\\Worldometer\\" + dt + ".csv");
if(!f.exists()) {
try {
//Create FileWriter object with file as parameter
CSVWriter writer = new CSVWriter(new FileWriter(f, true));
//Write headers
String[] headers = "Country/Region, Total Cases, New Cases, Total Deaths, New Deaths, Total Recovered, Active Cases, Serious Cases, Tot Cases/1M pop, Deaths/1M pop, Total Tests, Tests/1M pop".split(",");
writer.writeNext(headers);
writer.flush();
writer.close();
//Give full modification permissions to file
SetPermissions sp = new SetPermissions();
sp.ChangePermissions(f);
}catch (Exception ex) {
ex.printStackTrace();
}
}
else {
}
path = Paths.get(home + "\\Climate Dev Pegasus\\Data\\Worldometer\\" + dt + ".csv");
//Write data to file, allowing commas
FileWriter csvWriter = new FileWriter(f,true);
for(ArrayList<String> x : data) {
for(String y : x) {
String z = appendDQ(y);
//int value = Integer.parseInt(z);
csvWriter.append(z);
csvWriter.append(",");
}
csvWriter.append("\n");
}
System.out.println("Data successfully written to file.");
csvWriter.close();
}
最佳答案
这是我在思考这个问题时想到的答案:
嗯,我认为这是一个非常基本的问题。
首先,最重要的一点。该程序应该易于其他开发人员理解,同时它应该足够强大,以便最终用户在使用过程中不会受到干扰,例如长时间的加载时间。 但要找到问题的答案,你应该走得更远。该程序应该在 PC 上运行还是在嵌入式系统上运行? 由于Java已经默认实现了string类,因此它从头开始就非常强大。当然,整数总是性能更高,因为它是原始数据类型!现在我假设给定的程序应该在 PC 或服务器上运行,而不是在嵌入式系统上运行,因为对于这种情况,像 C 这样的语言会更合适。 我认为在这种情况下,使用字符串实际上更有意义,因为舒适的 Java 代码可以节省开发时间,并使代码对于其他开发人员来说更具可读性。此外,使用字符串可能需要额外的方法来将值转换为后续程序可以读取的格式。但是,这会抵消任何性能优势。
最后但并非最不重要的一点是,此时可以引用一个有趣的示例。如果以 CSV 格式导出 Excel 表,则也会在其中构建具有长字符串的文件。即使在那里,任何加载时间都不会打扰最终用户(在我看来)......
关于java - 将数据值作为整数类型而不是字符串写入 CSV 有哪些优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62475795/