我还没有测试过,但是下面的代码应该可以解决你的问题。
List<String> input = FileUtils.readLines(new File("SomeFile"), StandardCharsets.UTF_8);
List<String> output = new ArrayList<String>();
if(input.size()>1){
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
int month = cal.get(Calendar.MONTH) + 1;
String header = input.get(0) + ",monthsTill";
output.add(header);
int length = input.size();
for(int i=1;i<length;i++){
StringBuilder str = new StringBuilder();
String row = input.get(i);
String [] elements = row.split(",");
if(elements.length == 2){
// You have access to both the index and expiry date. So if you want to skip some row, simply don't add it to the ouput collection
int exp = Integer.parseInt(elements[1].substring(0, 2));
int monRemaining = month-exp;
str.append(row).append(",").append(monRemaining);
output.add(str.toString());
} else {
throw new IllegalArgumentException();
}
}
FileUtils.writeLines(new File("SomeFile"), output, false);
请注意,'FileUtils' 类来自 APache Commons IO 包
编辑:如果您不想使用 FileUtils,请替换
List<String> input = FileUtils.readLines(new File("SomeFile"), StandardCharsets.UTF_8);
与
List<String> input = new ArrayList<String>();
File inputFile = new File("SomeFile");
BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile));
String readLine = "";
while ((readLine = bufferedReader.readLine()) != null) {
input.add(readLine);
}
和
FileUtils.writeLines(new File("SomeFile"), output, false);
与
PrintWriter f0 = new PrintWriter(new FileWriter("SomeFile",false));
f0.print("");
// Erase the contents of the input file in a
// Very bad way
f0.close();
f0 = new PrintWriter(new FileWriter("output.txt"));
for(String row : output)
{
f0.println(row);
}
f0.close();
当然,如果您不使用 Apache Commons IO,您将不得不自己处理诸如流等关闭资源。