这是一个如何将文件读入字符串的示例:
public String readDocument(File document)
throws SystemException {
InputStream is = null;
try {
is = new FileInputStream(document);
long length = document.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new SystemException("Could not completely read file: " + document.getName());
}
return new String(bytes);
} catch (FileNotFoundException e) {
LOGGER.error("File not found exception occurred", e);
throw new SystemException("File not found exception occurred.", e);
} catch (IOException e) {
LOGGER.error("IO exception occurred while reading file.", e);
throw new SystemException("IO exception occurred while reading file.", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOGGER.error("IO exception occurred while closing stream.", e);
}
}
}
}