将文件转换为字符串。
在Java中将常见文件类型(.txt, .epub, .pdf)转换为字符串的最佳方法是什么?我想将它添加到我的android应用程序中,但我不想支付许可费。有没有好的开源库可以做到这一点?
看这篇文章:http://www.programcreek.com/2011/11/java-convert-a-file-into-a-string/
你不可能在一个API中拥有所有3种文件格式,但对于PDF格式,我建议
PDFBox
这是一个用于操作PDF文件的开源java API…
下面是一个将文本文件读入字符串的方法。它只返回原始文本。如果你想把pdf和其他电子书格式翻译成人类可读的字符串,你需要找到你想要处理的每种类型的库。
static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";
public static String readFileToString(String filePath, String encoding) throws IOException {
if (encoding == null || encoding.length() == 0)
encoding = DEFAULT_ENCODING;
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filePath));
byte[] buffer = new byte[BUFF_SIZE];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1)
content.append(new String(buffer, 0, bytesRead, encoding));
fis.close();
return content.toString();
}