以下示例使用 Java 7 的try
-with-resources 语句;如果您针对的是较早的平台,则必须手动关闭流。
final int MAX_BYTES = 1024 * 1024 * 10;
final int NEWLINE_BYTES = System.getProperty("line.separator")
.getBytes("UTF-8").length;
int bytesWritten = 0;
int fileIndex = 0;
while (existsMoreData()) {
try (
FileOutputStream fos = new FileOutputStream(
getFileNameForIndex(fileIndex));
OutputStreamWriter osr = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osr)) {
String toWrite = getCurrentStringToWrite();
int bytesOfString = toWrite.getBytes("UTF-8").length;
if (bytesWritten + bytesOfString + NEWLINE_BYTES > MAX_BYTES
|| bytesWritten == 0 /* if this part > MAX_BYTES */ ) {
// need to start a new file
fileIndex++;
bytesWritten = 0;
continue; // auto-closed because of try-with-resources
} else {
bw.write(toWrite, 0, toWrite.length());
bw.newLine();
bytesWritten += bytesOfString + NEWLINE_BYTES;
incrementDataToWrite();
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
可能的实现:
String[] data = someLongString.split("\n");
int currentPart = 0;
private boolean existsMoreData() {
return currentPart + 1 < data.length;
}
private String getCurrentStringToWrite() {
return data[currentPart];
}
private void incrementDataToWrite() {
currentPart++;
}
private String getFileNameForIndex(int index) {
final String BASE_NAME = "/home/codebuddy/somefile";
return String.format("%s_%s.txt", BASE_NAME, index);
// equivalent to:
// return BASE_NAME + "_" + index + ".txt";
}