SRP - single responsibility principle
The code is violating the SRP, as it does to many things.
It is
- adding/composing headers for the attachments
- reading files from disc
I would extract the composition of the headers to a separate method.
private String getHeaders() {
StringBuilder sb = new StringBuilder();
sb.append("\r\n").append("--").append(bound).append("\r\n");
sb.append("Content-Type: application/octet-stream\r\n");
sb.append("Content-Transfer-Encoding: base64\r\n");
sb.append("Content-Disposition: attachment; filename=\"");
return sb.toString();
}
and would assign the result before the for
loop to a String
variable.
Next we extract the file reading to a separate method. I don't know if Android
supports Try with resources so I don't use it here. We also rename the int nRead
to bytesRead
.
private byte[] readFile(File file) throws FileNotFoundException, IOException {
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int bytesRead;
byte[] data = new byte[1024];
while ((bytesRead= fileInputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytesRead);
}
buffer.flush();
fileInputStream.close();
return buffer.toByteArray();
}
next, we add a method which takes a file and returns the content as base64 encoded string
private String getContentAsBase64(File file) throws FileNotFoundException, IOException {
byte[] fileContent = readFile(file);
return Base64.encodeBase64String(fileContent);
}
After using the fluent append()
method instead of the string adding using +
, this leads to the former code beeing refactored to
Writer w = client.sendMessageData();
String attachmentHeader = getAttachmentHeader();
for (File file : myAttachments) {
w.append(attachmentHeader);
w.append(Tools.getNameForAttach(file.getName()));
w.append("\"\r\n\r\n");
w.append(getContentAsBase64(file));
w.append("\r\n");
}
w.close();
for (File f : myAttachments) {body.attachFile(f.getPath());}
– rolfl Nov 3 '14 at 12:09