这是一个简单的问题,如何打印出选定的文件名,谢谢。
public class CSVMAX {
public CSVRecord hottestInManyDays() {
//select many csv files from my computer
DirectoryResource dr = new DirectoryResource();
CSVRecord largestSoFar = null;
//read every row and implement the method we just define
for(File f : dr.selectedFiles()) {
FileResource fr = new FileResource(f);
CSVRecord currentRow = hottestHourInFile(fr.getCSVParser());
if (largestSoFar == null) {
largestSoFar = currentRow;
}
else {
double currentTemp = Double.parseDouble(currentRow.get("TemperatureF"));
double largestTemp = Double.parseDouble(largestSoFar.get("TemperatureF"));
//Check if currentRow’s temperature > largestSoFar’s
if (currentTemp > largestTemp) {
//If so update largestSoFar to currentRow
largestSoFar = currentRow;
}
}
}
return largestSoFar;
}
这里我想打印出文件名,但我不知道该怎么做。
public void testHottestInManyDay () {
CSVRecord largest = hottestInManyDays();
System.out.println("hottest temperature on that day was in file " + ***FILENAME*** + largest.get("TemperatureF") +
" at " + largest.get("TimeEST"));
}
}
最佳答案
最终,hottestInManyDays()
似乎需要返回此信息。
CSVRecord
有相应的属性吗?
类似这样的事情:
CSVRecord currentRow = hottestHourInFile(fr.getCSVParser());
currentRow.setFileName(f.getName());
如果没有的话可以添加这样的属性吗?
也许 CSVRecord
没有该属性。但是可以添加吗?:
private String _fileName;
public void setFileName(String fileName) {
this._fileName = fileName;
}
public String getFileName() {
return this._fileName;
}
如果没有,您能为这两条信息创建一个包装类吗?
如果您无法修改 CSVRecord
并且它没有地方存放您想要的信息,请将其包装在一个可以存放信息的类中。就这么简单:
class CSVWrapper {
private CSVRecord _csvRecord;
private String _fileName;
// getters and setters for the above
// maybe also a constructor? make them final? your call
}
然后从 hottestInManyDays()
返回那个,而不是 CSVRecord
。像这样的事情:
CSVWrapper csvWrapper = new csvWrapper();
csvWrapper.setCSVRecord(currentRow);
csvWrapper.setFileName(f.getName());
当然,根据需要更改方法签名和返回值。
<小时/>无论您如何执行此操作,一旦它位于 hottestInManyDays()
的返回值上,您就可以在使用该值的方法中使用它:
CSVWrapper largest = hottestInManyDays();
System.out.println("hottest temperature on that day was in file " + largest.getFileName() + largest.getCSVRecord().get("TemperatureF") +
" at " + largest.getCSVRecord().get("TimeEST"));
(注意:如果最后的位不符合德米特定律,那么请随意扩展包装器以根据需要包含直通操作。甚至可以让它共享一个公共(public)接口(interface)与 CSVRecord
一起使用,因此可以根据系统其他地方的需要将其用作直接替代品。)
关于java - 请注意文件名以及如何打印我从计算机中选择的文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36578333/