你可以尝试这样的事情:
public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
assert column >= 0 : "column < 0";
final List<String> lines = new LinkedList<String>();
final Scanner reader = new Scanner(file, "UTF-8");
while(reader.hasNextLine()){
final String line = reader.nextLine().trim();
if(line.isEmpty())
continue;
final String[] tokens = line.split(",");
assert column < tokens.length-1 : "column > tokens.length-1";
tokens[column] = replacement;
final StringBuilder builder = new StringBuilder();
for(final String token : tokens)
builder.append(token + ",");
for(final String append : appends)
builder.append(append + ",");
builder.deleteCharAt(builder.length()-1);
lines.add(builder.toString());
}
reader.close();
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
for(final String line : lines){
writer.write(line);
writer.newLine();
}
writer.flush();
writer.close();
}
或者,如果您使用的是 Java 8,则可以尝试以下操作:
public void replace(final int column, final String replacement, final File file, final String... appends) throws IOException {
assert column >= 0 : "column < 0";
final List<String> lines = new LinkedList<>();
final Scanner reader = new Scanner(file, "UTF-8");
while(reader.hasNextLine()){
final String line = reader.nextLine().trim();
if(line.isEmpty())
continue;
final String[] tokens = line.split(",");
assert column < tokens.length-1 : "column > tokens.length-1";
tokens[column] = replacement;
final List<String> temp = new LinkedList<>();
temp.addAll(Arrays.asList(tokens));
temp.addAll(Arrays.asList(appends));
lines.add(temp.stream().collect(Collectors.joining(",")));
}
reader.close();
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
lines.forEach(
l -> {
try{
writer.write(l);
writer.newLine();
}catch(IOException ex){
ex.printStackTrace();
}
}
);
writer.flush();
writer.close();
}
要调用此方法,您可以执行以下操作:
replace(3, "string to replace 12345", file, strings_you_want_to_append_to_the_end);